- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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)
- 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
- Related Articles
- Program to count number of paths whose sum is k in python
- Program to find number of consecutive subsequences whose sum is divisible by k in Python
- Program to count number of fraction pairs whose sum is 1 in python
- Count of n digit numbers whose sum of digits equals to given sum in C++
- n-th number whose sum of digits is ten in C++
- Count pairs from two linked lists whose sum is equal to a given value in C++
- Count ways to express a number as sum of consecutive numbers in C++
- C++ program to find range whose sum is same as n
- Python program for sum of consecutive numbers with overlapping in lists
- Count pairs (a, b) whose sum of cubes is N (a^3 + b^3 = N) in C++
- Count pairs (a, b) whose sum of squares is N (a^2 + b^2 = N) in C++
- Minimum number of single digit primes required whose sum is equal to N in C++
- Find M-th number whose repeated sum of digits of a number is N in C++
- Program to Count number of binary strings without consecutive 1’s in C/C++?
- C/C++ Program to Count number of binary strings without consecutive 1’s?

Advertisements