• Post Reply Bookmark Topic Watch Topic
  • New Topic

Tutorial Question  RSS feed

 
Sally Fox
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Everyone,

I need to write a function which, taking a positive integer n as input,
and finds all sets of numbers that sum up to n.
For example, n=4, the printing result will be:
4
3,1
2,2
2,1,1
1,1,1,1

So far my code is


public static void sum(int now,int remainder, int sum ){

System.out.println(now);

if (now == sum)
return;

if (remainder == sum)
{
remainder = 0;
sum(now++,remainder,sum);
return;
}
else{
sum(now,remainder++,sum);
return;
}
}
}

Please do help.^ ^
 
K. Tsang
Bartender
Posts: 3648
16
Firefox Browser Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

First question to ask yourself, if the function only takes in one input why your current approach has 3 inputs?

A hint is recursion. Given the input (say n=4), then this variable n decrements each time/cycle, keeping the remaining part. Do the same process on the remaining part until this part becomes 0. Go back to the first part (decremented n) and decrement again ... repeat

In fact your function is using recursion by calling itself ... but just with extra inputs.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Likes 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Step 1:
Throw that code away.

Step 2:
Turn off your computer. Get some paper and pencils.

Step 3:
Work out on paper how you would come up with a list. Then work out how you would explain to a 10-yr old child how to come up with the list.

Step 4:
Revise your directions several times, simplifying each step, making them more and more explicit.


Once you have done that, THEN you start writing java.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!