Problem Statement
This problem is asking us to find out the number of ways a natural number N can be expressed as a sum of two or more consecutive natural numbers. For example:
- 5 can be expressed as 2+3. This gives us the count as 1.
- 9 can be expressed as 4+5 and 2+3+4. This gives us the count as 2.
- 8 cannot be expressed as sum of consecutive numbers, so this gives us the count as 0.
Solution
Let us express N as a sum of n consecutive numbers as follows:
N = a + (a+1) + (a+2) + ... + (a+n-1)
N = (2a + n - 1) * n / 2
N = (2an + n2 - n ) / 2
a = (2N - n2 + n ) / 2n
Now, if a is a positive number then RHS will also be positive. Loop until RHS is positive as every positive natural number value of RHS is one possible answer.
Example Code
public class Sample{
public static void main(String[] args) {
double N = 7;
double count = 0;
double n = 2;
for(double i=2; i<10; i++) {
n = i;
double val = (2*N - n*n + n ) / ( 2*n );
if(val - (int)val == 0 && val > 0) {
count++;
}
}
System.out.println("count is: " + count);
}
}
This code returns the following output:
count is: 2.0