# Program to count number of consecutive lists whose sum is n in C++

Suppose we have a number n, we have to find the number of lists of positive consecutive values that sum up to n.

So, if the input is like n = 15, then the output will be 4, as The possible lists are: [1, 2, 3, 4, 5], [4, 5, 6], [7, 8], and [15].

To solve this, we will follow these steps:

• begin := 1, end := 1, x := (n + 1)
• sum := 0
• while end <= x, do:
• sum := sum + end
• while sum >= n, do:
• if sum is same as n, then:
• (increase count by 1)
• sum := sum - begin
• (increase begin by 1)
• (increase end by 1)
• return count + 1

Let us see the following implementation to get better understanding:

## Example

Live Demo

#include
using namespace std;

int solve(int n) {
int begin=1,end=1,x=(n+1)/2,count=0;
long int sum=0;
while(end <= x){
sum += end;
while(sum >= n){
if(sum == n)
count++;
sum -= begin;
begin++;
}
end++;
}
return count+1;
}
main(){
cout << (solve(15));
}

## Input

15

## Output

4

Advertisements