- Related Questions & Answers
- 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++
- Numbers With Same Consecutive Differences in C++
- Check if a number can be expressed as a sum of consecutive numbers in C++
- Maximum consecutive numbers present in an array in C++
- Check three consecutive numbers - JavaScript
- N consecutive odd numbers JavaScript
- Consecutive elements sum array in JavaScript
- Divide Array in Sets of K Consecutive Numbers in C++
- Remove Zero Sum Consecutive Nodes from Linked List in C++
- Sum of Square Numbers in C++
- Program to print numbers such that no two consecutive numbers are co-prime and every three consecutive numbers are co-prime Using C++
- JavaScript to check consecutive numbers in array?
- Finding three desired consecutive numbers in JavaScript

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

#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)); }

10

2

Advertisements