![]() |
VOOZH | about |
Given a positive integer n, find whether it can be represented as the sum of two or more consecutive positive integers.
Examples:
Input: n = 10
Output: true
Explanation: 10 can be expressed as: 1 + 2 + 3 + 4 = 10.
Input: n = 8
Output: false
Explanation: 8 cannot be expressed as the sum of two or more consecutive positive integers.
Input: n = 24
Output: true
Explanation: 24 can be expressed as: 7 + 8 + 9 = 24.
Table of Content
The idea is to start from every number and keep adding consecutive numbers until the sum becomes equal to or greater than
n. If the sum becomes equal ton, return"true".
The sum of first n natural numbers is: n * (n + 1) / 2.
The sum of first (x + k) natural numbers is: (x + k) * (x + k + 1) / 2.
If n is the sum of k consecutive numbers, then:
n = [(x + k)(x + k + 1) - x(x + 1)] / 2
Or,
2 * n = [(x + k)(x + k + 1) - x(x + 1)]
So, we try all possible values and check whether the condition becomes true.
true
The idea is that a number can be written as the sum of consecutive positive numbers if it is not a power of
2. So, we simply check whethernis a power of2using bit manipulation.
Why a Power of 2 cannot be expressed?
The idea is based on the fact that every sum of consecutive integers must have at least one odd factor greater than 1. Let us see the proof.
Sum of k consecutive numbers 𝑘(2𝑎 + k - 1) / 2 = n
The above equation can be written as k(2a + k - 1) = 2n.
If k is even, then (k-1) is odd. Adding 2a (Which is even) to an odd number results in an odd number. Thus, one of these factors must be odd and the other must be even.
Why all other numbers can be expressed?
Every odd number n can be written as (2m + 1) which can be written as m + (m+1) which is sum of two consecutive.
true