#### Recursive Digit Sum

I was trying to solve this problem on hackerrank. But I got some problem. Specific problem is:

For example:

1. The sum of digits 9875 will be calculate as:

sum(9875) = 9+8+7+5 = 29.

sum(29) = 11.

sum(11) = 2. (Using recursive function).

2. In my test case, (n =’9875′, k=4) the number p is created by concatenating the string n k times so the initial p = 9875987598759875 ( the string ‘9875’ repeat 4 times ).

But when i code this test case, it doesn’t work. Here is my source code:

``````int SuperDigit(long n){
long sum =0;
if(n==0) return 0;
else{
return sum= sum +(n%10 + SuperDigit(n/10));
}
if(sum>10){
return (sum%10 + SuperDigit(sum/10));
}

}

int main(){
string n;cin>>n;
int T;cin>>T;
string repeat;
for(int i=0; i <T;i++){
repeat += n;
}
cout<<repeat;
long x=0;
stringstream geek(repeat);
geek>>x;
long sum = SuperDigit(x);
printf("n%ld ",sum);
for(int i=0;i<10;i++){
if(sum>=10){
sum = SuperDigit(sum);
}
else{
break;
}
}
printf("n%ld ",sum);
}
``````

If i try: n = ‘123’ and k =3 (Expected output: 9)

My output will be correct, here is my output for this test case:

``````123 3
123123123
18
9
``````

But when i try n = ‘9875’ and k = 4 (Expected output: 8)

My output will be wrong:

``````9875 4
9875987598759875
46
1
``````

As you can see in this test case, the first sum of all digits must be 116. But mine only show 46.

Can anyone explain for me? Thanks a lot!

Source: Windows Questions C++