In Java, can someone help me figure this out? Find the number of ways that a giv
ID: 3846868 • Letter: I
Question
In Java, can someone help me figure this out?
Find the number of ways that a given integer, X. can be expressed as the sum of the N ^th power of unique, natural numbers. The first line contains an integer X. The second line contains an integer N. 1 lessthanorequalto X lessthanorequalto 1000 2 lessthanorequalto N lessthanorequalto 10 Output a single integer, the answer to the problem explained above. If X = 10 and N = 2, we need to find the number of ways that 10 can be represented as the sum of squares of unique numbers. 10 = 1^2 - 3^2 This is the only way in which 10 can be expressed as the sum of unique squares. 100 = 10^2 = 6^2 + 8^2 = 1^2 + 3^2 + 4^2 + 5^2 + 7^2 100 can be expressed as the sum of the cubes of 1, 2, 3, 4. (1 + 8 + 27 + 64 = 100). There is no other way to express 100 as the sum of cubes.Explanation / Answer
Please find my program.
import java.util.Scanner;
public class NthPower {
// Function to calculate and return the
// power of any given number
static int power(int num, int n)
{
if (n == 0)
return 1;
else if (n%2 == 0)
return power(num, n/2)*power(num, n/2);
else
return num*power(num, n/2)*power(num, n/2);
}
static int countWays(int x, int n) {
return checkRecursive(x, n, 1, 0);
}
// Function to check power representations recursively
static int checkRecursive(int x, int n, int curr_num, int curr_sum)
{
// Initialize number of ways to express
// x as n-th powers of different natural
// numbers
int results = 0;
// Calling power of 'i' raised to 'n'
int p = power(curr_num, n);
while (p + curr_sum < x)
{
// Recursively check all greater values of i
results += checkRecursive(x, n, curr_num+1,
p+curr_sum);
curr_num++;
p = power(curr_num, n);
}
// If sum of powers is equal to x
// then increase the value of result.
if (p + curr_sum == x)
results++;
// Return the final result
return results;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter x value: ");
int x = sc.nextInt();
System.out.print("Enter n value: ");
int n= sc.nextInt();
sc.close();
System.out.println("Number of ways: "+countWays(x, n));
}
}
/*
Sample run:
Enter x value: 10
Enter n value: 2
Number of ways: 1
Enter x value: 100
Enter n value: 2
Number of ways: 3
Enter x value: 100
Enter n value: 3
Number of ways: 1
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.