Consecutive Numbers Sum in C++

C++Server Side ProgrammingProgramming

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

 Live Demo

#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
raja
Published on 04-Jun-2020 11:31:25
Advertisements