programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

Tutorial Question

Sally Fox
Greenhorn
Posts: 1
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
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
• 3
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.