gogoWebsite

The sum of continuous positive integers

Updated to 2 days ago

The sum of continuous positive integers

Given a positive integer, how do you determine whether it is the sum of a continuous positive integer?

For example, given a positive integer 15, it can be represented as 15 = 1 + 2 + 3 + 4 + 5, or it can be represented as 15 = 7 + 8.

Given a positive integer 6, it can be represented as 6 = 1 + 2 + 3.

So what are the characteristics of such positive integers? What kind of numbers can be represented as the sum of consecutive positive integers? What kind of number cannot be represented as the sum of consecutive positive integers?

Obviously, all odd numbers can be represented as the sum of consecutive positive integers, such as n = (n - 1) / 2 + (n + 1) / 2.

So what about an even number?

When an even number is n = 2 ^ k (k >= 1), it cannot be represented as the sum of consecutive positive integers, such as even numbers such as 2, 4, 8, 16... Other forms of even numbers can be represented as the sum of consecutive positive integers.

When judging in the code, it can be judged based on the bitwise and bit operator (&).

If n satisfies

n & (n - 1) == 0

Then it cannot be represented as the sum of a continuous positive integer, otherwise it can be represented.