Sally Fox

Greenhorn

Posts: 1

posted 4 years ago

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

Please do help.^ ^

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.^ ^

posted 4 years ago

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.

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.

K. Tsang OCPJP7 OCMJEA6

posted 4 years ago

- 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.

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.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors