Check if a number can be expressed as a sum of consecutive numbers
Last Updated :
30 Sep, 2023
Given a number n, the task is to check whether it can be expressed as a sum of two or more consecutive numbers or not.
Example
Input : n = 10
Output : true
It can be expressed as sum of two consecutive
numbers 1 + 2 + 3 + 4.
Input : n = 16
Output : false
It cannot be expressed as sum of two consecutive
numbers.
Input : n = 5
Output : true
2 + 3 = 5
There is a direct and quick method to solve this. If a number is a power of two, then it cannot be expressed as a sum of consecutive numbers otherwise Yes.
The idea is based on below two facts.
1) Sum of any two consecutive numbers is odd as one of them has to be even and the other odd.
2) 2n = 2n-1 + 2n-1
If we take a closer look at 1) and 2), we can get the intuition behind the fact.
Below is the implementation of the above idea.
C++
// C++ program to check if a number can
// be expressed as sum of consecutive numbers
#include<bits/stdc++.h>
using namespace std;
// This function returns true if n can be
// expressed sum of consecutive.
bool canBeSumofConsec(unsigned int n)
{
// We basically return true if n is a
// power of two
return ((n&(n-1)) && n);
}
// Driver code
int main()
{
unsigned int n = 15;
canBeSumofConsec(n)? cout << "true" :
cout << "false";
return 0;
}
Java
// Java program to check if a number can
// be expressed as sum of consecutive numbers
class Test
{
// This function returns true if n can be
// expressed sum of consecutive.
static boolean canBeSumofConsec(int n)
{
// We basically return true if n is a
// power of two
return (((n&(n-1))!=0) && n!=0);
}
// Driver method
public static void main(String[] args)
{
int n = 15;
System.out.println(canBeSumofConsec(n) ? "true" : "false");
}
}
Python3
# Python 3 program to check if a number can
# be expressed as sum of consecutive numbers
# This function returns true if n
# can be expressed sum of consecutive.
def canBeSumofConsec(n) :
# We basically return true if n is a
# power of two
return ((n&(n-1)) and n)
# Driver code
n = 15
if(canBeSumofConsec(n)) :
print("true")
else :
print("false")
# This code is contributed by Nikita Tiwari.
C#
// C# program to check if a number can be
// expressed as sum of consecutive numbers
using System;
class Test
{
// This function returns true if n
// can be expressed sum of consecutive.
static bool canBeSumofConsec(int n)
{
// We basically return true if n is a
// power of two
return (((n & (n - 1)) != 0) && n != 0);
}
// Driver Code
public static void Main()
{
int n = 15;
Console.Write(canBeSumofConsec(n) ? "True" : "False");
}
}
// This code is contributed by Nitin Mittal.
JavaScript
<script>
// Javascript program to check if a number can
// be expressed as sum of consecutive numbers
// This function returns true if n can be
// expressed sum of consecutive.
function canBeSumofConsec(n)
{
// We basically return true if n is a
// power of two
return (((n&(n-1))!=0) && n!=0);
}
// function call
let n = 15;
document.write(canBeSumofConsec(n) ? "true" : "false");
</script>
PHP
<?php
// php program to check if a number
// can be expressed as sum of
// consecutive numbers
// This function returns true if n
// can be expressed sum of consecutive.
function canBeSumofConsec($n)
{
// We basically return true if n is a
// power of two
return (($n & ($n - 1)) && $n);
}
// Driver code
$n = 15;
if(canBeSumofConsec($n))
echo "true" ;
else
echo "false";
// This code is contributed by
// nitin mittal.
?>
Time Complexity: O(1)
Auxiliary Space: O(1)
Another Approach :
Let number chosen to represent N as a sum of consecutive numbers be X + 1, X + 2, X + 3 .... Y
Sum of these chosen numbers = Sum of first Y natural numbers - Sum of first X natural number
Sum of first Y natural number = \frac {Y \cdot (Y + 1)} {2}
Sum of first X natural number = \frac {X \cdot (X + 1)} {2}
We know that, N = Sum of first Y natural number - Sum of first X natural number N = \frac {Y \cdot (Y + 1)} {2} - \frac {X \cdot (X + 1)} {2}
2N = Y \cdot (Y + 1) - X \cdot (X + 1)
2N = Y ^ 2 - X ^ 2 + Y - X
2N = (Y - X) \cdot (Y + X + 1)
Let Y - X = a, Y + X + 1 = b Y + X + 1 > Y - X, b > a X = \frac {a - b - 1} {2}
, Y = \frac {a + b + 1} {2}
2N = a * b It means that a and b are factor of 2N, we know that X and Y are integers so, 1. b - a - 1 => multiple of 2 (Even number) 2. b + a + 1 => multiple of 2 (Even number)
Both conditions must be satisfied
From 1 and 2 we can say that either one of them (a, b) should be Odd and another one Even
So if the number (2N) has only odd factors (can't be possible as it is an even number (2N not N) ) or only even factors we can't represent it as a sum of any consecutive natural numbers
So now, we have to now only check whether it has an odd factor or not
1. If the number (2N not N) does not have any odd factor (contains only even factor means can be represented as 2 ^ k
) then we can't represent it as a sum of consecutive number
2. If the number (2N not N) has an odd factor then we can represent it as a sum of a consecutive number
After this we have to only check whether we can represent (2N as 2^k
) or not
- if Yes then answer is false or 0
- if No then answer is true or 1
Below is the implementation of the above idea :
C++14
#include <bits/stdc++.h>
using namespace std;
long long int canBeSumofConsec(long long int n)
{
// Updating n with 2n
n = 2 * n;
// (n & (n - 1)) => Checking whether we can write 2n as 2^k
// if yes (can't represent 2n as 2^k) then answer 1
// if no (can represent 2n as 2^k) then answer 0
return ((n & (n - 1)) != 0);
}
int main()
{
long long int n = 10;
cout<<canBeSumofConsec(n)<<"\n";
}
C
#include <stdio.h>
long long int canBeSumofConsec(long long int n)
{
// Updating n with 2n
n = 2 * n;
// (n & (n - 1)) => Checking whether we can write 2n as 2^k
// if yes (can't represent 2n as 2^k) then answer 1
// if no (can represent 2n as 2^k) then answer 0
return ((n & (n - 1)) != 0);
}
int main()
{
long long int n = 10;
printf("%lld", canBeSumofConsec(n));
}
Java
import java.util.*;
class GFG{
static int canBeSumofConsec( int n)
{
// Updating n with 2n
n = 2 * n;
// (n & (n - 1)) => Checking whether we can write 2n as 2^k
// if yes (can't represent 2n as 2^k) then answer 1
// if no (can represent 2n as 2^k) then answer 0
return ((n & (n - 1)) != 0)?1:0;
}
public static void main(String[] args)
{
int n = 10;
System.out.print(canBeSumofConsec(n)+"\n");
}
}
// This code is contributed by umadevi9616
Python3
def canBeSumofConsec(n):
# Updating n with 2n
n = 2 * n;
# (n & (n - 1)) => Checking whether we can write 2n as 2^k
# if yes (can't represent 2n as 2^k) then answer 1
# if no (can represent 2n as 2^k) then answer 0
if((n & (n - 1)) != 0):
return 1;
else:
return 0;
if __name__ == '__main__':
n = 10;
print(canBeSumofConsec(n));
# This code is contributed by umadevi9616
C#
using System;
public class GFG {
static int canBeSumofConsec(int n)
{
// Updating n with 2n
n = 2 * n;
// (n & (n - 1)) => Checking whether we can write 2n as 2^k
// if yes (can't represent 2n as 2^k) then answer 1
// if no (can represent 2n as 2^k) then answer 0
return ((n & (n - 1)) != 0) ? 1 : 0;
}
public static void Main(String[] args) {
int n = 10;
Console.Write(canBeSumofConsec(n) + "\n");
}
}
// This code is contributed by umadevi9616
JavaScript
<script>
function canBeSumofConsec(n) {
// Updating n with 2n
n = 2 * n;
// (n & (n - 1)) => Checking whether we can write 2n as 2^k
// if yes (can't represent 2n as 2^k) then answer 1
// if no (can represent 2n as 2^k) then answer 0
return ((n & (n - 1)) != 0) ? 1 : 0;
}
var n = 10;
document.write(canBeSumofConsec(n) + "\n");
// This code is contributed by umadevi9616
</script>
Time Complexity: O(1)
Auxiliary Space: O(1)
Approach#3:Using Brute Force
Start a loop from 1 to n/2 (inclusive) For each value i in the loop, start another loop from i+1 to n/2+1 (inclusive) Calculate the sum of consecutive numbers from i to j If the sum is equal to n, return True If the sum is greater than n, break the inner loop and start the next iteration of the outer loop If no consecutive sum is found, return False
Algorithm
1. Define a function is_sum_of_consecutive_numbers(n)
2. Start a loop from 1 to n/2 (inclusive)
3. For each value i in the loop, start another loop from i+1 to n/2+1 (inclusive)
4. Calculate the sum of consecutive numbers from i to j
5. If the sum is equal to n, return True
6. If the sum is greater than n, break the inner loop and start the next iteration of the outer loop
7. If no consecutive sum is found, return False
C++
#include <iostream>
bool is_sum_of_consecutive_numbers(int n) {
for (int i = 1; i < (n / 2 + 2); i++) {
for (int j = i + 1; j < (n / 2 + 2); j++) {
int sum_consecutive = (j - i + 1) * (i + j) / 2;
if (sum_consecutive == n) {
return true;
}
else if (sum_consecutive > n) {
break;
}
}
}
return false;
}
int main() {
int n = 10;
std::cout << std::boolalpha << is_sum_of_consecutive_numbers(n) << std::endl;
// This Code Is Contributed By Shubham Tiwari.
return 0;
}
Java
public class Main {
// Function to check if a given number 'n' can be expressed as the sum of consecutive numbers
public static boolean isSumOfConsecutiveNumbers(int n) {
// Iterate through possible consecutive number combinations
for (int i = 1; i < (n / 2 + 2); i++) {
for (int j = i + 1; j < (n / 2 + 2); j++) {
// Calculate the sum of consecutive numbers between 'i' and 'j'
int sumConsecutive = (j - i + 1) * (i + j) / 2;
// If the calculated sum matches 'n', it can be expressed as consecutive numbers
if (sumConsecutive == n) {
return true;
} else if (sumConsecutive > n) {
// If the sum exceeds 'n', there's no need to continue with larger 'i' values
break;
}
}
}
// If no consecutive number sum matches 'n', return false
return false;
}
public static void main(String[] args) {
int n = 10;
// Check if 'n' can be expressed as the sum of consecutive numbers and print the result
System.out.println(isSumOfConsecutiveNumbers(n));
// This code is contributed by Shivam Tiwari
}
}
Python3
def is_sum_of_consecutive_numbers(n):
for i in range(1, n//2+2):
for j in range(i+1, n//2+2):
sum_consecutive = (j-i+1)*(i+j)//2
if sum_consecutive == n:
return True
elif sum_consecutive > n:
break
return False
n=10
print(is_sum_of_consecutive_numbers(n))
C#
using System;
class GFG
{
// Function to check if a number can be represented
// as the sum of consecutive numbers
static bool IsSumOfConsecutiveNumbers(int n)
{
for (int i = 1; i < (n / 2 + 2); i++)
{
for (int j = i + 1; j < (n / 2 + 2); j++)
{
int sumConsecutive = (j - i + 1) * (i + j) / 2;
if (sumConsecutive == n)
{
return true;
}
else if (sumConsecutive > n)
{
break;
}
}
}
return false;
}
static void Main(string[] args)
{
int n = 10;
Console.WriteLine($"{IsSumOfConsecutiveNumbers(n)}");
// This Code Is Contributed By Shubham Tiwari.
}
}
JavaScript
// Function to check if a number can be represented
// as the sum of consecutive numbers
function is_sum_of_consecutive_numbers(n) {
//loop from 1 to n/2+1
for (let i = 1; i < (n / 2 + 2); i++) {
//loop from i+1 to n/2+1
for (let j = i + 1; j < (n / 2 + 2); j++) {
//sum of consecutive numbers from i to j
let sum_consecutive = (j - i + 1) * (i + j) / 2;
//When sum is equal to n
if (sum_consecutive == n) {
return true;
}
else if (sum_consecutive > n) {
break;
}
}
}
//When no consecutive sum is found
return false;
}
let n = 10;
console.log(is_sum_of_consecutive_numbers(n));
Time complexity: O(n^2)
Space complexity: O(1)
Reference:
http://www.cut-the-knot.org/arithmetic/UnpropertyOfPowersOf2.shtml
Similar Reads
Express a number as sum of consecutive numbers
Given a number N, write a function to express N as sum of two or more consecutive positive numbers. If there is no solution, output -1. If there are multiple solution, then print one of them.Examples: Input : N = 10 Output : 4 + 3 + 2 + 1 Input : N = 8 Output : -1 Input : N = 24 Output : 9 + 8 + 7 R
5 min read
Check if a number can be expressed as sum two abundant numbers
Given a number N. The task is to express N as the sum of two Abundant Numbers. If it is not possible, print -1. Examples:Input : N = 24 Output : 12, 12Input : N = 5Output : -1 Approach: An efficient approach is to store all abundant numbers in a set. And for a given number, N runs a loop from 1 to n
13 min read
Check if a prime number can be expressed as sum of two Prime Numbers
Given a number n, the task is to check if it is possible to express n as the sum of two prime numbers, a and b. If such pair does not exist, return [-1, -1].Note: If [a, b] is one solution with a <= b, and [c, d] is another solution with c <= d, and a < c then [a, b] is considered as our an
9 min read
Number expressed as sum of five consecutive integers
Given an integer n, the task is to find whether n can be expressed as sum of five consecutive integer. If yes, find the five consecutive integers, else print â-1â.Examples: Input : n = 15 Output : 1 2 3 4 5 15 = 1 + 2 + 3 + 4 + 5 Input : n = 18 Output : -1 Method 1: (Brute Force) The idea is to run
11 min read
Check if a number can be written as sum of three consecutive integers
Given an integer n, the task is to find whether n can be written as sum of three consecutive integer. If yes, find the three consecutive integer, else print "-1".Examples: Input: n = 6Output: 1 2 3Explanation: 6 = 1 + 2 + 3. Input: n = 7Output: -1 Recommended PracticeCheck for three consecutive numb
10 min read
Count prime numbers that can be expressed as sum of consecutive prime numbers
Given an integer N, the task is to find the number of prime numbers up to N that can be expressed as a sum of consecutive primes. Examples: Input: N = 45Output: 3Explanation:Below are the prime numbers up to 45 that can be expressed as sum of consecutive prime numbers: 5 = 2 + 317 = 2 + 3 + 5 + 741
8 min read
Check if a number can be expressed as 2^x + 2^y
Given a number n, we need to check if it can be expressed as 2x + 2y or not . Here x and y can be equal.Examples : Input : 24 Output : Yes Explanation: 24 can be expressed as 24 + 23 Input : 13 output : No Explanation: It is not possible to express 13 as sum of two powers of 2. If we take few exampl
9 min read
Check if a number N can be expressed in base B
Given a number N and any base B. The task is to check if N can be expressed in the form a1*b0 + a2*b1 + a3*b2 + ....+ a101*b100 where each coefficients a1, a2, a3...a101 are either 0, 1 or -1. Examples: Input: B = 3, N = 7 Output: Yes Explanation: The number 7 can be expressed as 1 * 30 + (-1) * 31
6 min read
Check if a number can be represented as sum of two consecutive perfect cubes
Given an integer N, the task is to check if this number can be represented as the sum of two consecutive perfect cubes or not. Examples: Input: N = 35Output: YesExplanation:Since, 35 = 23 + 33, therefore the required answer is Yes. Input: N = 14Output: No Naive Approach: The simplest approach to sol
7 min read
Check if given number can be represented as sum of two great numbers
We are given a number N. We need to check if the given number N can be represented as sum of two Great numbers. If yes then print those two great numbers else print no. Great numbers are those which are represented in the form : ((b)*(b+1)*(2*b+1))/6 where b is a natural number. Examples: Input : N
7 min read