packagecom.thealgorithms.backtracking;importjava.util.Scanner;publicclassPowerSum{publicstaticvoidmain(String[] args){Scanner sc =newScanner(System.in);System.out.println("Enter the number and the power");intN= sc.nextInt();intX= sc.nextInt();PowerSum ps =newPowerSum();int count = ps.powSum(N,X);//printing the answer.System.out.println("Number of combinations of different natural number's raised to "+X+" having sum "+N+" are : ");System.out.println(count);
sc.close();}privateint count =0, sum =0;publicintpowSum(intN,intX){Sum(N,X,1);return count;}//here i is the natural number which will be raised by X and added in sum.publicvoidSum(intN,intX,int i){//if sum is equal to N that is one of our answer and count is increased.if(sum ==N){
count++;return;}//we will be adding next natural number raised to X only if on adding it in sum the result is less than N.elseif(sum +power(i,X)<=N){
sum +=power(i,X);Sum(N,X, i +1);//backtracking and removing the number added last since no possible combination is there with it.
sum -=power(i,X);}if(power(i,X)<N){//calling the sum function with next natural number after backtracking if when it is raised to X is still less than X.Sum(N,X, i +1);}}//creating a separate power function so that it can be used again and again when required. privateintpower(int a,int b){return(int)Math.pow(a, b);}}