Https://www.hackerrank.com/challenges/the-power-sum/problem


this code is not working properly for the given problem plz correct the recursive code along with explaination…

I don’t think why you have complicated it so much. Here is a much simpler approach which uses recursion as the question demands.

int func(int x,int n,int k) {

if(pow(k,n)<x)
{
return(func(x,n,k+1)+func(x-pow(k,n),n,k+1));
}
else if(pow(k,n)==x)
return 1;
else
return 0;

}
int main() {
int x,n;
scanf("%d%d",&x,&n);
int total=func(x,n,1);
printf("%d",total);
return 0;
}

if u could correct my code it would be much better …as i will know where i was wrong…

I cannot understand why you are calculating the kth root when you are trying to solve the problem using recursion. Just run it for all n?

but ans will not go beyond kth root that is why as all numbers are positive…

The thing is you can add that as base condition like this
if(pow(k,n)<x)
{
return(func(x,n,k+1)+func(x-pow(k,n),n,k+1));
}

That is the whole essence of recursion. Leaving the program to solve for itself, it’s a good programming practice and easier to debug.

ok but plz correct my code for this time …i will follow this practice from ny onwards…

Here I corrected your code https://ide.codingblocks.com/s/251388

while passing in recursion we should do i+1 and not i++ because that inc value of i …is this correct??

yes that is correct.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.