2021-03-28: Define a number: a number that can be expressed as the sum of several (number>1) consecutive positive numbers. For example: 5 = 2+3,

2021-03-28: Define a number: a number that can be expressed as the sum of several (number>1) consecutive positive numbers. For example: 5 = 2+3, 5 is such a number; 12 = 3+4+5, 12 is such a number. 1 is not such a number, because the number is required to be greater than 1, and the sum of consecutive positive numbers. 2 = 1 + 1, and 2 is not because the right side of the equal sign is not a continuous positive number. Given a parameter N, return whether it can be expressed as a number of consecutive positive numbers.

Fu Da's answer 2021-03-28:

1. Natural wisdom.
Sliding window. Midpoint to 1. L shifts to the left, and increases; R shifts to the left, and decreases. If sum = N, it is true.

2. Reverse the results based on the results and find the rules.
N is the power of 2 and cannot be expressed as the sum of consecutive positive numbers; N is not the power of 2 but is the number of the sum of consecutive positive numbers.

The code is written in golang. code show as below:

package main

import "fmt"

func main() {
    for i := 1; i <= 64; i++ {
        fmt.Println(i, isMSum1(i), isMSum2(i))
    }
}

func isMSum1(num int) bool {
    if num == 1 {
        return false
    }
    R := (num + 1) >> 1
    L := R - 1
    sum := R
    for {
        if sum == num {
            return true
        } else if sum > num {
            sum -= R
            R--
        } else {
            if L == 0 {
                break
            }
            sum += L
            L--

        }
    }
    return false
}
func isMSum2(num int) bool {
    return num != (num & (^num + 1))
    //return num != (num & (-num))

    //return (num & (num - 1)) != 0
}

The execution results are as follows:
image


Left god java code
comment

Guess you like

Origin blog.51cto.com/14891145/2675549