[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

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

 

 

Solution 1 of runtime O(sqrt(N))  that you came up.

Because we must find consecutive numbers that sum up to N, so for a given length K, we can only have at most 1 valid sequence. Based on this, we can solve this problem by looping through all possible length and check if a given length can provide a valid sequence. This will not cause TLE because we only need to check up to O(sqrt(N)) possible length. Why is this?

 

Proof: if we have a sequence from 1 to J, then we have sum (1 + J) * J / 2. This sum is the smallest for any sequence of length J. (1 + J) * J / 2 <= N. So the length of any valid sequence can only go up to O(sqrt(N)), any sequence that is longer will have a sum that is > N. 

 

Use binary search to find the upper bound of sequence length in O(logN) time.

 

The problem then is converted to check if a given length K can have a valid sequence in O(1) time, since we want to get a overall O(sqrt(N)) runtime. We achieve this by the following 3 observations.

1. base case: K = 1, the sequence is N itself; K = 2 and N is odd, the sequence is N / 2, N / 2 + 1.

2. if K is odd and we have a valid sequence of such length. Let's denote the middle number A[mid]. We have A[mid - 1] + A[mid + 1] = A[mid] * 2, A[mid - 2] +A[mid + 2] = A[mid] * 2, and so on. This means K * A[mid] == N, N is divisible by K.

3. if K is even and we have a valid sequence of such length A[j1, j2], we group the sequence in this fashion: A[j1] + A[j2], A[j1 + 1], A[j2 - 1], A[j1 + 2], A[j2 - 2], and so on. We have K / 2 pairs of equal sum N / (K / 2). One of the pair is the middle 2 consecutive numbers. This means the pair sum must be odd as the sum of 2 consecutive numbers is always odd. So we must also have (N / (K / 2)) % 2 != 0.

 

class Solution {
    public int consecutiveNumbersSum(int N) {       
        int ways = 1;
        if(N % 2 != 0 && N > 1) {
            ways++;
        }
        int maxLen = 0;
        long l = 1, r = N;
        while(l < r - 1) {
            long mid = l + (r - l) / 2;
            if((mid + 1) * mid / 2 <= N) {
                l = mid;
            }
            else {
                r = mid - 1;
            }
        }
        if((r + 1) * r / 2 <= N) {
            maxLen = (int)r;    
        }
        else {
            maxLen = (int)l;
        }
        for(int len = 3; len <= maxLen; len++) {
            if(len % 2 != 0 && N % len == 0) {
                ways++;
            }          
            else if(len % 2 == 0 && N % (len / 2) == 0 && (N / (len / 2)) % 2 != 0){
                ways++;
            }
        }
        return ways;
    }
}

 

Another O(sqrt(N)) solution

 

For a given sequence length K, the smallest sum we'll have is 1 + 2 + 3 + ..... + K, then we'll have 2 + 3 + 4 + ..... + K + (K + 1). Subtract each number by 1 then compensate the difference at the end we have 1 + 2 + 3 + ...... + K + K. In general, if we start the sequence at B, we'll have 1 + 2 + 3 + ..... + K + (B - 1) * K.

 

The above observation means for a given length K, we can form such a sequence that sum up to N only if N - (1 + 2 + 3 + .... + K) is divisible by K. As discussed in solution 1, we only need to check up to O(sqrt(N)) possible lengths. 

 

class Solution {
    public int consecutiveNumbersSum(int N) {
        int ways = 0;
        for(long len = 2; (1 + len) * len / 2 <= N; len++) {
            if((N - (1 + len) * len / 2) % len == 0) {
                ways++;
            }
        }
        return ways + 1;
    }
}

 

 

Solution that wows everyone: Counting odd numbers by applying prime factorization

For given length K, if there is a valid sequence, we then have N = (x + 1) + (x + 2) + .... + (x + K) = K * x + K * (K + 1) / 2, where x >= 0, K >= 1. 

N * 2 = K * (2 * x + K + 1). If K is even, then 2 * x + K + 1 is odd; If 2 * x + K + 1 is even, then k must be odd. Either K or 2 * x + K + 1 is odd. 

This means for each odd factor of N, we can find a valid consecutive sequence. Now the problem becomes finding all the unique odd factors of N. Each different odd factor represents one different valid sequence. To do this, we apply the prime factorization algorithm because any odd factor can be generated by combining non-2 prime factors. So for each non-2 prime factor p, if the current answer count is C, we add another C to the final answer. Why? Because for all previous C sequences, whatever odd factor each sequence maps to, we multiply that factor by p to get a new factor. Since we are only dealing with prime factors, each multiplication operation generates an unique odd factor. So if p appears T(p) times in N's prime factorization, we add T(p) * C to C, which is equivalent to C *= (T(p) + 1). 

 

Algorithm

1.  First ignore all factors of 2. Then starting from 3 and for each possible prime number, divide N by it until can't. 

2. Just like the prime factorization algorithm, if N is not 1 after exiting the for-loop, it means we've got a biggest prime factor that only appears once. Add its contribution toward the final answer in this case.

 

 

class Solution {
    public int consecutiveNumbersSum(int N) {
        int ways = 1, cnt = 0;
        while(N % 2 == 0) {
            N /= 2;
        }
        for(int i = 3; i * i <= N; i += 2) {
            cnt = 0;
            while(N % i == 0) {
                N /= i;
                cnt++;
            }
            ways *= (cnt + 1);
        }
        return N == 1 ? ways : ways * 2;
    }
}

 

上一篇:面向对象程序设计第一单元总结(求导程序)


下一篇:IIS 禁止自动回收