- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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

Advertisements