【Lintcode】1439. Consecutive Numbers Sum

题目地址:

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

给一个数字 N N ,问有多少种方法可以将其写成连续的若干正整数之和。

N = [ a + ( a + ( k 1 ) b ) ] k 2 N=\frac{[a+(a+(k-1)b)]k}{2} ,解得 a = N k k 1 2 a=\frac{N}{k}-\frac{k-1}{2} 其中 a a 为首项, k k 为项数。所以我们只需要从 k = 1 k=1 开始枚举 k k 即可。显然 k k 越大则解出来的 a a 越小,当解出小于 1 1 a a 时循环就终止。代码如下:

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;
    }
}

时间复杂度 O ( N ) O(\sqrt{N}) ,只需注意到不等式 N k k 1 2 1 \frac{N}{k}-\frac{k-1}{2}\ge 1 ,推出 k 2 + k 2 N k^2+k\le 2N ,然后即得结论。

发布了387 篇原创文章 · 获赞 0 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/105464937