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
Start with sum = 0.
Let 1 be the current number.
Add the current number to the sum.
If sum > N
, subtract numbers from the first number added to the sum until sum <= N
.
Stop if sum = N
(success).
Increase the current number.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With