I have struggle on this one for a whole day. Can anyone help me on this? Thanks!
ID: 3739036 • Letter: I
Question
I have struggle on this one for a whole day. Can anyone help me on this? Thanks!
This is a very challenging question. Good luck! There are 11 different ways to write a sum of positive integers (greater than 0) that add up to 6, if the order of the numbers doesn't matter: 6 4+2 3+2+1 2+2+2 2+2+1+1 Note that the numbers are always written in descending order. (Only 5+1, never 1+5.) Start with the file TemplateLab10Gold.java Complete the method void printAllSums (int n) which will print all of the ways to write a sum of positive integers that add up to n, exactly as shown above (for n-6). This method will not be recursive itself. It should simply call the one below. (It should be a 1-line method.) Create a more general recursive version of printAl1Sums, with an extra parameter or two, which will allow the sums to be easily computed and printed. The single-parameter version above should call this one. Note that this will be a very short method, but it may be difficult to figure out how to do it. Look at the patterns in the example above and try to spot a simple recursion. Good luck. Run the supplied main program which will test your methods for n-1, 2, and 6 1. 2. 3. 4.Explanation / Answer
class Main
{
public static void main(String[] args)
{
int num=6;
printAllsums(num);
}
public static void printAllsums(int num)
{
int temp = num,count=1;
System.out.println(num);
for(num=6;num>1;num--)
{
System.out.print(num-1);
while(num+count-2!=temp)
{
System.out.print(" + "+count);
count++;
int dc=(count-1);
int ic=1;
while(dc!=1)
{
while((count-ic-1)!=1)
{
System.out.print(" "+(num-1));
System.out.print(" + "+(dc-ic)+" + "+ic);
ic++;
}
dc--;
}
}
System.out.println();
}
}
}