目录
一、原题
原题链接 Which are in?
Instructions
Some numbers have funny properties. For example:
- 89 --> 8¹ + 9² = 89 * 1
- 695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2
- 46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51
Given two positive integers n
and p
, we want to find a positive integer k
, if it exists, such that the sum of the digits of n
raised to consecutive powers starting from p
is equal to k * n
.
In other words, writing the consecutive digits of n
as a, b, c, d ...
, is there an integer k
such that :
(𝑎𝑝+𝑏𝑝+1+𝑐𝑝+2+𝑑𝑝+3+...)=𝑛∗𝑘(ap+bp+1+cp+2+dp+3+...)=n∗k
If it is the case we will return k
, if not return -1
.
Note: n
and p
will always be strictly positive integers.
Examples:
|
二、解题
1.读题
1)此题结合所给公式
,digPow(int n, int p)传入的n和p即为公式中的n和p。a,b,c,d等字母表示的为n从高到底各位上的值。
2)此题是找K,使n和p传入是上式子能成立,返回K值;若不能成立,返回-1;
n = 89; p = 1 ---> 1 since 8¹ + 9² = 89 = 89 * 1
该例子中 存在整数k=1,使式子成立,故返回k值(1);
n = 92; p = 1 ---> -1 since there is no k such that 9¹ + 2² equals 92 * k
该例子中 不存在整数k,使式子成立,故返回k值-1;
2、思路
1) 通过int k(int n,int p),求传入的n和p,对应的下式的值
从高位求各位的值,并按式子求和
int k(int n,int p){
int item=1,sum=0;
while(item<n){
item*=10;
}
item/=10;
while(n>0){//从高位到低位,依次取各位数值,按要求将其相加
sum+=pow((n/item),p);
p+=1;
n=n%item;
item/=10;
}return sum;
}
2)将上个面所求值存入data中,通过if(data%n==0)判断是否存在整数K,存在则返回K(data/n),否则返回-1;
data=k(n,p);
if(data%n==0){
return data/n;
}
else return -1;
3、Myway
#include<stdio.h>
#include<math.h>
int k(int n,int p){
int item=1,sum=0;
while(item<n){
item*=10;
}
item/=10;
while(n>0){//从高位到低位,依次取各位数值,按要求将其相加
sum+=pow((n/item),p);
p+=1;
n=n%item;
item/=10;
}return sum;
}
int digPow(int n, int p) {
int data=0;
if(n==0){
return 0;
}
data=k(n,p);
if(data%n==0){
return data/n;
}
else return -1;
}
三、总结
1、理解题意,便于做题
2、写功能函数,简化主题代码,可清晰思路,便于查错,提高效率