
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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)
- if sum is same as n, then:
- (increase end by 1)
- return count + 1
Let us see the following implementation to get better understanding:
Example
#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