-9

I want to write a code in Java which inputs any integer value by the user and gives a output as sum of consecutive numbers=input. All possibilities.

Eg

Input 15 Output

  1. 7+8
  2. 4+5+6
  3. 1+2+3+4×5

1 Answers1

1

Suppose you have tried to come up with any algorithm by yourself, you should find out that brutal algorithm is not quite possible to solve this problem. I assume what you need is an algorithm instead of the code itself.

Let's assume all integers in the range [a,b] summing up to your input. So you will end up with this equation (b+a) (b-a+1) / 2 = input. In your case where input = 15, (b+a) and (b-a+1) would be two of the factors of input * 2, which is 30.

Therefore, there are four possibilities for (a,b)

  1. (b+a, b-a+1) = (30, 1), so (a,b)=(15,15)
  2. (b+a, b-a+1) = (15, 2), so (a,b)=(7,8)
  3. (b+a, b-a+1) = (10, 3), so (a,b)=(4,6)
  4. (b+a, b-a+1) = (6, 5), so (a,b)=(1,5)

In summary, this problem is essentially to ask you how to factor a number.

Wen-Bin Luo
  • 147
  • 1
  • 15