829. Consecutive Numbers Sum

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:

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

Example 2:

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

Example 3:

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

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

题目大意

求正整数 N,有多少种方法可以把它写成连续正整数的和?

解题思路

由题目规律可得:
N / c 为 第c / 2 + c % 2个数,所以 N / c >= c / 2 + c % 2
符合下列情况时,存在连续正整数的和为 N
c 为奇数,N 可以整除 c
c 为偶数,并且 (N / c) * c + c / 2 == N

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
func consecutiveNumbersSum(_ N: Int) -> Int {
var ans = 0
var c = 0
while true {
c += 1
if N / c < c / 2 + c % 2 {
break
}
if c % 2 == 1 && N % c == 0 {
ans += 1
}else if c % 2 == 0 && (N / c) * c + c / 2 == N {
ans += 1
}
}
return ans
}
}
0%