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的正等差数列的和的方式有多少种。
思考
首先是等差数列的求和,对于这道题的公式就是:
N=(i+1)∗i2+(i+1)∗a N = ( i + 1 ) ∗ i 2 + ( i + 1 ) ∗ a
其中数据满足:
- a>0 a > 0
- i>=0 i >= 0
具体的思路就是将i
从0到N进行迭代,计算
(i+1)∗i2
(
i
+
1
)
∗
i
2
和N
的大小,可知
(i+1)∗i2<=N
(
i
+
1
)
∗
i
2
<=
N
成立,如果发现
(i+1)∗i2>N
(
i
+
1
)
∗
i
2
>
N
就可以停止迭代,再计算是否存在对应的a
,判断是否满足条件即可。
代码实现
class Solution {
public:
int consecutiveNumbersSum(int num) {
int result = 0;
for (int i = 0; i < num; ++i) {
if (i * (i + 1) / 2 > num) {
break;
}
int as = num - (i + 1) * i / 2;
// 不能整除继续
if (as % (i + 1) != 0)continue;
// 开始的数字a大于0
if (as / (i + 1) > 0){
++result;
}
}
return result;
}
};
感想
数学是有用滴。