leetcode 829. Consecutive Numbers Sum

Given a positive integer N, how many ways can we write it as a sum of consecutive positive integers?

Example 1:

Input: 5
Output: 2
Explanation: 5 = 5 = 2 + 3

Example 2:

Input: 9
Output: 3
Explanation: 9 = 9 = 4 + 5 = 2 + 3 + 4

Example 3:

Input: 15
Output: 4
Explanation: 15 = 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5

Note: 1 <= N <= 10 ^ 9.

解题思路:

这其实就是一道公差为1的等差数列题 ;

=> a1 * n + n * (n - 1) / 2 == N ;

=> a1 == N / n - (n - 1) / 2 ;

因为a1 >= 1 , 所以 N / n >= (n - 1) / 2 ; => n <= sqrt(2 * N) ;

且因为 a1 为整数 , 当n % 2 == 1 && N % n == 0  ||  n % 2 == 0 && N % n == n / 2  时 a1才为整数 ;

class Solution {
public:
    int consecutiveNumbersSum(int N) 
    {
        int res = 0 , n = 1 , a1 = 0 ;
        
        while(n <= sqrt(2 * N))
        {
            if(n % 2 == 1 && N % n == 0 )
            {
                a1 = N / n - (n - 1) / 2 ;
                if(a1 < 1 || a1 > N ) break ;
                res++ ;
            }
            else if(n % 2 == 0 && N % n == n / 2)
            {
                a1 = (N - n / 2) / n - (n - 1) / 2 ;
                if(a1 < 1 || a1 > N ) break ;
                res++ ;
            }       
            n++ ;
        }
        
        return res ;
    }
};

 

上一篇:刷题128. Longest Consecutive Sequence


下一篇:带你读《中台战略:中台建设与数字商业》之三:云智慧时代的数字营销