Consecutive Numbers Sum

HardMathmath

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given a positive integer n, count how many different ways it can be written as a sum of one or more **consecutive positive integers**. A single number on its own counts as a run of length one, so every n has at least one way (itself). Two ways are different if their runs start at different numbers. Return the count. Aim for roughly O(sqrt(n)) time: iterating over every possible starting number is far too slow for n near 10^9.

Examples

Input: n = 5
Output: 2
5 = 5 and 5 = 2 + 3.
Input: n = 9
Output: 3
9 = 9, 9 = 4 + 5, and 9 = 2 + 3 + 4.
Input: n = 15
Output: 4
15 = 15 = 7 + 8 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5.

Constraints

  • 1 <= n <= 10^9

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More math problems