Algorithm
Problem Name: 829. Consecutive Numbers Sum
Given an integer n
, return the number of ways you can write n
as the sum of consecutive positive integers.
Example 1:
Input: n = 5 Output: 2 Explanation: 5 = 2 + 3
Example 2:
Input: n = 9 Output: 3 Explanation: 9 = 4 + 5 = 2 + 3 + 4
Example 3:
Input: n = 15 Output: 4 Explanation: 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5
Constraints:
1 <= n <= 109
Code Examples
#1 Code Example with Javascript Programming
Code -
Javascript Programming
const consecutiveNumbersSum = function (N) {
let count = 1
for (let k = 2; k < Math.sqrt(2 * N); k++) {
if ((N - (k * (k - 1)) / 2) % k === 0) count++
}
return count
}
Copy The Code &
Try With Live Editor
Input
n = 5
Output
2
#2 Code Example with Python Programming
Code -
Python Programming
class Solution:
def consecutiveNumbersSum(self, N):
cnt=0
for d in range(1, N+1):
diff=d*(d-1)//2
nd = N - diff
if nd<=0: break
if nd%d==0:
cnt+=1
return cnt
Copy The Code &
Try With Live Editor
Input
n = 5
Output
2
#3 Code Example with C# Programming
Code -
C# Programming
using System;
namespace LeetCode
{
public class _0829_ConsecutiveNumbersSum
{
public int ConsecutiveNumbersSum(int N)
{
var upper = (int)(Math.Sqrt(2 * N + 0.25) - 0.5);
var count = 0;
for (int i = 1; i < = upper; i++)
{
N -= i;
if (N % i == 0) count++;
}
return count;
}
}
}
Copy The Code &
Try With Live Editor
Input
n = 9
Output
3