Consecutive integers sum

Subject description:

Given a positive integer N, Determine how many sets of consecutive positive integers satisfy all the numbers sum to N?

Example 1:

Input: 5
Output: 2
Explanation: 5 = 3 + 2 = 5, a total of two consecutive integers ([5], [2,3]) is the sum 5.
Example 2:

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

Input: 15
Output: 4
Explanation: 15 = 15 = 8 + 4 + 5 + 7 = 1 + 6 = 2 + 3 + 4 + 5
Description:. 1 < = N < = 10 ^. 9

 

analysis:

In an example N = 15,

1, 15;

2, 7 + 8;

3, 4 + 5 + 6;

5, 1 + 2 + 3 + 4 + 5;

......

N = x * n + n * (n-1) / 2, N being a positive integer input, n is an number, a group number x is the smallest number, it exists and if x is a positive integer, is satisfied;

 

Codes are as follows:

// Returns the number of result sets qualifying
func consecutiveNumbersSum(_ N: Int) -> Int {
    was Sum 0
    for i in 1..<Int.max {
        let tmp = N - ((i-1)*i)/2
        if tmp < i {
            break
        }
        
        var x = -1
        
        if tmp % i == 0 && tmp / i > 0 {
            x = tmp / i
            sum += 1
           
           // print qualifying group
            was nums = [int] ()
            for j in 0..<i {
                nums.append(x+j)
            }
            print("\(i): \(nums)")
        }
        
        if x <= 1 && x != -1 {
            break
        }
    }
    return sum
}

  

  

Guess you like

Origin www.cnblogs.com/mustard22/p/11094372.html