# Check if a number can be written as sum of three consecutive integers 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

In this section we will see, whether a number can be represented as tree consecutive numbers or not. Suppose a number is 27. This can be represented as 8 + 9 + 10.

This can be solved in two different approach. The first approach is Naïve approach. In that approach, we have to check i + (i + 1) + (i + 2) is same as number or not. Another efficient approach is by checking whether the number is divisible by 3 or not. Suppose a number x can be represented by three consecutive 1s, then x = (y - 1) + y + (y + 1) = 3y. So the number must be divisible by 3.

## Example

Live Demo

#include <iostream>
using namespace std;
bool hasThreeNums(int n) {
if(n % 3 == 0){
return true;
}
return false;
}
int main() {
int num = 27;
if(hasThreeNums(num)){
cout << "Can be represented";
}else{
cout << "Cannot be presented";
}
}

## Output

Can be represented