829. Consecutive Numbers Sum
HardView on LeetCode
Time: O(√n)
Space: O(1)
Problem Overview
Consecutive Numbers Sum (Hard) asks you to solve a structured algorithmic task. This is a common Math pattern in coding interviews. For each k, check if (n - k(k-1)/2) is positive and divisible by k; count valid partitions.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
For each k, check if (n - k(k-1)/2) is positive and divisible by k; count valid partitions.
Related patterns: Math
829.cs
C#
// Approach: For each k, check if (n - k(k-1)/2) is positive and divisible by k; count valid partitions.
// Time: O(√n) Space: O(1)
public class Solution
{
public int ConsecutiveNumbersSum(int n)
{
int ans = 0;
for (int i = 1, triangleNum = i; triangleNum <= n; ++i, triangleNum += i)
if ((n - triangleNum) % i == 0)
++ans;
return ans;
}
}Was this solution helpful?
Related Problems
- 12. Integer to Roman(Medium)
- 13. Roman to Integer(Easy)
- 29. Divide Two Integers(Medium)
- 66. Plus One(Easy)
- 67. Add Binary(Easy)
- 70. Climbing Stairs(Easy)