Write a program in Java to allow the user to enter a natural number.
Now generate and display all the possible combinations of natural numbers that add up to the given natural number.
Display a suitable error message and terminate the program if a valid natural number is not entered.
Example 1:
INPUT: N = 5
OUTPUT:
1 1 1 1 1
1 1 1 2
1 1 3
1 2 2
1 4
2 3
5
Example 2:
N = 0
OUTPUT:
Please enter a natural number.
import java.io.*;
class Generate{
public static void main(String[] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("N = ");
int n = Integer.parseInt(br.readLine());
if(n < 1){
System.out.println("Please enter a natural number.");
return;
}
find(n);
}
public static void generate(int a[], int index, int n, int reduced){
if(reduced < 0)
return;
if(reduced == 0){
for (int i = 0; i < index; i++)
System.out.print (a[i] + " ");
System.out.println();
return;
}
int prev = (index == 0)? 1 : a[index - 1];
for(int k = prev; k <= n ; k++){
a[index] = k;
generate(a, index + 1, n, reduced - k);
}
}
public static void find(int n){
int arr[] = new int [n];
generate(arr, 0, n, n);
}
}
2 replies on “Combinations of Numbers that add up to given Sum”
Sir,a program is given which states that:
WAP in java to accept some numbers to
create m × m matrix(where m=size of the Matrix where m must be greater than 3 and less than 10).Display the elements above the right diagonal of that matrix.(Using Scanner class)
Here is the link to the solution to your problem. I have used BufferedReader. You can modify it for Scanner class.