# 829.Consecutive Numbers Sum

**829.Consecutive numbers sum**

题目难度 Medium

> 给定一个正整数 N，试求有多少组连续正整数满足所有数字之和为 N?

```
示例 1:
输入: 5
输出: 2
解释: 5 = 5 = 2 + 3，共有两组连续整数([5],[2,3])求和后为 5。
示例 2:
输入: 9
输出: 3
解释: 9 = 9 = 4 + 5 = 2 + 3 + 4
示例 3:
输入: 15
输出: 4
解释: 15 = 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5
说明: 1 <= N <= 10 ^ 9
```

需要注意的是，当N比较大时，因为int类型的表达范围，sqrt计算根时会丢失数据，如`8*N`则可改为`8.0*N`转换为float或者double。 最初方法一： 根据等差数列求和公式，对于首项x1计算出项数n，然后通过求和比较是否和为N，x1从1循环到N，但这种方式只适用于N比较小的情况，Leetcode这题会显示超时。

```
class Solution {
public:
    int consecutiveNumbersSum(int N) {
        int num=0;
        for(int i=1;i<=N;i++)
        {
            int n= (sqrt((2.0*i-1)*(2*i-1)+8*N)- 2*i +1)/2 ;
            if(n>0 && n*(i+i+n-1) == 2*N)
                num++;
        }
        return num;

    }
};
```

方法二：通过循环n来求出x1，因为n的数目不可能超过从1+..+xn=N中的xn，因此求出最大项数maxnum。然后同样用求和公式求出x1，最后进行求和比较，判断是否满足条件。测试时长:8ms

```
class Solution {
public:
    int consecutiveNumbersSum(int N) {
        int num=1;
        int maxnum= (sqrt(N*8.0+1)-1)/2;
        for(int n=2;n<=maxnum;n++)
        {
            int x1 = ((2*N)/n -n+1)/2;
            
            if(n*(x1*2+n-1) == 2*N)
            {
                num++;
               //printf("%d\t%d\n",x1,n);
            }
        }
        return num;
        
    }
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dfine.gitbook.io/leetcode/829.consecutive_numbers_sum.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
