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.
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 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.
Below is implementation of above idea.
This article is contributed by Sahil Chhabra(KILLER). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Check if a number can be expressed as sum two abundant numbers
- Check whether a number can be expressed as a product of single digit numbers
- Number expressed as sum of five consecutive integers
- Check if a prime number can be expressed as sum of two Prime Numbers
- Check if a number can be expressed as a^b | Set 2
- Check if a number can be expressed as 2^x + 2^y
- Check if a number can be expressed as power | Set 2 (Using Log)
- Check if a number can be expressed as x^y (x raised to power y)
- Check whether a number has consecutive 0's in the given base or not
- Express a number as sum of consecutive numbers
- Check if a number can be written as sum of three consecutive integers
- Find the number of consecutive zero at the end after multiplying n numbers
- Count ways to express a number as sum of consecutive numbers
- N expressed as sum of 4 prime numbers
- Count primes that can be expressed as sum of two consecutive primes and 1
Improved By : nitin mittal