做者: 負雪明燭
id: fuxuemingzhu
我的博客: http://fuxuemingzhu.cn/python
題目地址:https://leetcode.com/problems/consecutive-numbers-sum/ide
Given a positive integer N
, how many ways can we write it as a sum of consecutive positive integers?優化
Example 1:spa
Input: 5 Output: 2 Explanation: 5 = 5 = 2 + 3
Example 2:code
Input: 9 Output: 3 Explanation: 9 = 9 = 4 + 5 = 2 + 3 + 4
Example 3:leetcode
Input: 15 Output: 4 Explanation: 15 = 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5
Note: 1 <= N <= 10 ^ 9
.rem
問給定一個數字N,有多少種把它展開成連續正整數之和的方案。get
有些題會讓人陷入常規作法不能自拔,好比這個題就可能想成回溯或者O(M*N)的循環。事實上能夠經過數學方法進行優化。博客
由於是連續正整數之和,因此能夠使用數列求和公式直接求和,把O(M*N)的方案降到O(M)。數學
由N = a + (a + 1) + (a + 2) + (a + 3) + ... + (a + i)
得,
N = a * (i + 1) + (i * (i + 1)) / 2
,其中,a > 0
而且i>= 0
。
因此,咱們先求出prod = (i * (i + 1)) / 2 , 若是這個數字大於N了,就馬上結束。不然,remain = N - prod ==> a * (i + 1). 因此,remain應該可以整除(i + 1),並且餘數爲a > 0。
這個題用python代碼會超時,改用C++就能經過。
C++代碼以下:
class Solution { public: int consecutiveNumbersSum(int N) { int res = 0; for (int i = 0; i < N; i++) { int prod = (i + 1) * i / 2; if (prod > N) break; int remain = N - prod; if (remain % (i + 1) != 0) continue; if (remain / (i + 1) > 0) res ++; } return res; } };
2019 年 1 月 5 日 —— 美好的週末又開始了