这是我为解决HackerRank问题所写的代码"递归数字和" https://www.hackerrank.com/challenges/recursive-digit-sum ,代码假设采用两位数作为输入(n,k)来计算超级数字p。 当k连接n次时,如果k = 148且n = 3
,则创建pP = 148148148
sumdigit(P)= sumdigit(148148148)
= sumdigit(1 + 4 + 8 + 1 + 4 + 8 + 1 + 4 + 8)
= sumdigit(39)
= sumdigit(3 + 9)
= sumdigit(12)
= sumdigit(1 + 2)
= sumdigit(3)
= 3.
约束
1·; = N< 10 ^(100000)
1·; = K&LT = 10 ^ 5
#include <stdio.h>
#include <math.h>
unsigned long int SumDigits(unsigned long int i) {
if (i < 10) {
return i;
}
else {
return i%10 + SumDigits(i/10);
}
}
int main() {
unsigned long int n,k,pos=0;
scanf("%ld %ld",&k,&n);
/**i would put the constraint however it reduces the accepted test cases*/
// if(k>=1&&k<pow(10,100000)&&n>=1&&n<pow(10,5)){
for(unsigned long int i=0;i<n;i++){
pos+=k;
k=k*( unsigned long int)pow(10,n);
}
while(pos>=10){
pos=SumDigits(pos);
}
printf("%ld\n",pos);
//}
return 0;
}