# Check if a number can be expressed as a sum of consecutive numbers in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

Here we will see if one number can be represented as sum of two or more consecutive numbers or not. Suppose a number is 12. This can be represented as 3+4+5.

There is a direct and easiest method to solve this problem. If a number is power of 2, then it cannot be expressed as sum of some consecutive numbers. There are two facts that we have to keep in mind.

• Sum of any two consecutive numbers is odd, then one of them will be odd, another one is even.
• Second fact is 2n = 2(n-1) + 2(n-1).

## Example

Live Demo

#include <iostream>
using namespace std;
bool isSumofconsecutiveNumbers(int n) {
if((n & (n-1)) && n){
return true;
} else {
return false;
}
}
int main() {
int num = 36;
if(isSumofconsecutiveNumbers(num)){
cout << "Can be represented";
} else {
cout << "Cannot be represented";
}
}

## Output

Can be represented