【Lintcode】1439. Consecutive Numbers Sum

Title address:

https://www.lintcode.com/problem/consecutive-numbers-sum/description

Give a number N N , ask how many methods can be written as the sum of consecutive positive integers.

Assume N = [ a + ( a + ( k 1 ) b ) ] k 2 N=\frac{[a+(a+(k-1)b)]k}{2} ,Solutions have to a = N k k 1 2 a=\frac{N}{k}-\frac{k-1}{2} among them a a first item, k k is the number of items. So we just need to k = 1 k=1 Start enumeration k k enough. Obviously k k greater the , the better a a smaller a is, when the solution is less than 1 1 of a a , the loop is terminated. code show as below:

public class Solution {
    /**
     * @param N: an integer
     * @return: how many ways can we write it as a sum of consecutive positive integers
     */
    public int consecutiveNumbersSum(int N) {
        // Write your code here
        int res = 0, count = 1;
        double a = 1, num = (double) N;
        // 如果解出的首项小于1了,那就枚举结束
        while (a >= 1) {
        	// 解出首项
            a = num / count - (count - 1) / 2.0;
            // 如果首项是个正整数则计答案 + 1
            if (isInteger(a) && a >= 1) {
                res++;
            }
            // 枚举项数 + 1
            count++;
        }
        
        return res;
    }
    
    private boolean isInteger(double a) {
        return Math.abs(a - (int) a) <= 1E-10;
    }
}

time complexity O ( N ) O (\ sqrt {N}) , Just notice the inequality N k k 1 2 1 \frac{N}{k}-\frac{k-1}{2}\ge 1 , launch k 2 + k 2 N k ^ 2 + k \ and 2N , and then a conclusion is drawn.

Published 387 original articles · liked 0 · 10,000+ views

Guess you like

Origin blog.csdn.net/qq_46105170/article/details/105464937