- 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
Consecutive Numbers Sum in C++
Suppose we have a positive integer N, we have to find how many different ways can we write it as a sum of consecutive positive integers?
So, if the input is like 10, then the output will be 3, this is because we can represent 10 as 5 + 5 and 7 + 3, so there are two different ways.
To solve this, we will follow these steps −
ret := 1
for initialize i := 2, (increase i by 1), do −
sum := (i * (i + 1)) / 2
if sum > N, then −
Come out from the loop
rem := N - sum
ret := ret + (1 when rem mod i is 0, otherwise 0)
return ret
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: int consecutiveNumbersSum(int N) { int ret = 1; for(int i = 2; ; i++){ int sum = (i * (i + 1)) / 2; if(sum > N) break; int rem = N - sum; ret += (rem % i == 0); } return ret; } }; main(){ Solution ob;cout << (ob.consecutiveNumbersSum(10)); }
Input
10
Output
2
- Related Articles
- Sum of consecutive numbers in JavaScript
- Print all possible sums of consecutive numbers with sum N in C++
- Count ways to express a number as sum of consecutive numbers in C++
- The sum of two consecutive numbers are 45 find the numbers.
- Find two consecutive whole numbers whose sum is 19.
- Express the following numbers as the sum of consecutive odd numbers: $36$.
- Check if a number can be expressed as a sum of consecutive numbers in C++
- Python program for sum of consecutive numbers with overlapping in lists
- Numbers With Same Consecutive Differences in C++
- Find two consecutive numbers whose squares have the sum 85.
- Maximum consecutive numbers present in an array in C++
- The sum of the squares of two consecutive even numbers is 340. Find the numbers.
- The sum of the squares of three consecutive natural numbers is 149. Find the numbers.
- The sum of the squares of two consecutive odd numbers is 394. Find the numbers.
- The sum of three consecutive even number is 96 . Find the numbers

Advertisements