![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
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
Count ways to express a number as sum of consecutive numbers in C++
Given an integer n as input. The goal is to find the number of ways in which we can represent ‘num’ as the sum of two or more consecutive natural numbers. For example, if n is 3 it can be represented as sum ( 1+2 ) so total 1 way.
For Example
Input
num=6
Output
Count of ways to express a number as sum of consecutive numbers are: 1
Explanation
The ways in which we can express ‘num’ as sum of consecutive natural numbers: 1+2+3
Input
num=19
Output
Count of ways to express a number as sum of consecutive numbers are: 1
Explanation
The ways in which we can express ‘num’ as sum of consecutive natural numbers: 9+10
Approach used in the below program is as follows −
In this approach we will represent the number as the sum of ( a + a+1 + a+2…..+ a+i ).
Which becomes (a)(L+1) times + 1+2+3+4…+i = a*(i+1) + i*(i+1)/2. (sum of i natural numbers) num=a*(i+1) + i*(i+1)/2.a= [ num − (i)*(i+1)/2 ] / (i+1)
We will do this for i=1 to i*(i+1)/2 is less than num.
Take an integer num as input.
Function sum_consecutive(int num) takes a num and returns the count of ways to express ‘num’ as sum of consecutive natural numbers.
Take the initial count as 0.
Take temporary variable res as float.
Using for loop traverse from i=1 to i*(i+1)/2 < num.
Calculate the value [ num − (i)*(i+1)/2 ] / (i+1) and store in res.
If res is integer ( res − (int)res is 0 ) then increment count.
At the end we have count as ways in which num can be represented as the sum of consecutive natural numbers.
Return count as result.
Example
#include <bits/stdc++.h> using namespace std; int sum_consecutive(int num){ int count = 0; int temp = num * 2; float res; for (int i = 1; i * (i + 1) < temp; i++){ int store = i + 1; res = (1.0 * num−(i * (i + 1)) / 2) / store; float check = res − (int)res; if(check == 0.0){ count++; } } return count; } int main(){ int num = 20; cout<<"Count of ways to express a number as sum of consecutive numbers are: "<<sum_consecutive(num) << endl; return 0; }
Output
If we run the above code it will generate the following output −
Count of ways to express a number as sum of consecutive numbers are: 1