Check if a number can be expressed as a sum of consecutive numbers - GeeksforGeeks
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.
Read full article from Check if a number can be expressed as a sum of consecutive numbers - GeeksforGeeks
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.
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 other odd.
2) 2n = 2n-1 + 2n-1
1) Sum of any two consecutive numbers is odd as one of them has to be even and other odd.
2) 2n = 2n-1 + 2n-1
If we take a closer look at 1) and 2), we can get intuition behind the fact.
bool
canBeSumofConsec(unsigned
int
n)
{
// We basically return false if n is a
// power of two
return
((n&(n-1)) && n);
}