I was going through a simple program that takes a number and finds the number of occurrences of consecutive numbers that matches with given number.
For example:
if input is 15, then the consecutive numbers that sum upto 15 are:
1,2,3,4,5
4,5,6
7,8
So the answer is 3 as we have 3 possibilities here.
When I was looking for a solution I found out below answer:
static long process(long input) {
long count = 0;
for (long j = 2; j < input/ 2; j++) {
long temp = (j * (j + 1)) / 2;
if (temp > input) {
break;
}
if ((input- temp) % j == 0) {
count++;
}
}
return count;
}
I am not able to understand how this solves the requirement because this program is using some formula which I am not able to understand properly, below are my doubts:
- The for loop starts from 2, what is the reason for this?
long temp = (j * (j + 1)) / 2;
What does this logic indicates? How is this helpful to solving the problem?if ((num - temp) % j == 0)
Also what does this indicate?
Please help me in understanding this solution.
count = 0, input = 15, j = 2.
Thustemp = (2 * (2 + 1)) / 2 = 3
, and3 is not > 15
, so you do:(15 - 3) / 2
and since that is not equal to0
, add1
to the count. Now repeat it again withj = 3
and so on, untilj = 15/2
and then see what you have left in count.temp = (2 * (2 + 1)) / 2 = 3
and how this helps in solving the problem. I can understand what the program is doing but I want to know how these steps can solve the problem statement.