829. Consecutive Numbers Sum

Given a positive integer N, how many ways can we write it as a sum of consecutive positive integers?

Example 1:

Input: 5
Output: 2
Explanation: 5 = 5 = 2 + 3

Example 2:

Input: 9
Output: 3
Explanation: 9 = 9 = 4 + 5 = 2 + 3 + 4

Example 3:

Input: 15
Output: 4
Explanation: 15 = 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5

Note: 1 <= N <= 10 ^ 9.

Rust Solution

struct Solution;

impl Solution {
    fn consecutive_numbers_sum(n: i32) -> i32 {
        let mut i = 2;
        let mut res = 1;
        while i * i < 2 * n {
            if (n - i * (i - 1) / 2) % i == 0 {
                res += 1;
            }
            i += 1;
        }
        res
    }
}

#[test]
fn test() {
    let n = 5;
    let res = 2;
    assert_eq!(Solution::consecutive_numbers_sum(n), res);
    let n = 9;
    let res = 3;
    assert_eq!(Solution::consecutive_numbers_sum(n), res);
    let n = 15;
    let res = 4;
    assert_eq!(Solution::consecutive_numbers_sum(n), res);
    let n = 4;
    let res = 1;
    assert_eq!(Solution::consecutive_numbers_sum(n), res);
}

Having problems with this solution? Click here to submit an issue on github.