Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate the continuous sequence which sum up equal to N [closed]

Tags:

algorithm

math

Given a number N and generate an Arithmetic Progression having difference of 1 so that after summing up to finite element gives the number N for example:

For Example:
N=10
1 + 2 + 3 + 4 =10
N=20
2+3+4+5+6 = 20
N=30
4+5+6+7+8 = 30

N < 1000000

like image 435
Satish Patel Avatar asked Sep 27 '13 12:09

Satish Patel


Video Answer


1 Answers

  1. Start with sum = 0.

  2. Let 1 be the current number.

  3. Add the current number to the sum.

  4. If sum > N, subtract numbers from the first number added to the sum until sum <= N.

  5. Stop if sum = N (success).

  6. Increase the current number.

  7. Continue from step 3.

You'll just need to remember the first number added to the sum for step 4, which you will increase by one as you subtract it from the sum (thanks Niko).

As an optimization, you can also use a formula (n(n+1)/2) to add numbers in batch rather than adding them one by one (in case N is large).

Example:

N = 30

Sum = 0
Add 1 -> 1
Add 2 -> 3
Add 3 -> 6
Add 4 -> 10
Add 5 -> 15
Add 6 -> 21
Add 7 -> 28
Add 8 -> 36
36 > 30, so:
  Subtract 1 -> 35
  Subtract 2 -> 33
  Subtract 3 -> 30
Done.
like image 200
Bernhard Barker Avatar answered Nov 08 '22 01:11

Bernhard Barker