DEV Community

Discussion on: Daily Challenge #55 - Building a Pile of Cubes

Collapse
 
brightone profile image
Oleksii Filonenko • Edited

I did the naive iterative solution first, and then I saw the formula from Dominik G, and wanted to compare the two solutions.

Here are the two functions in Rust.

Iterative:

pub fn pile_of_cubes_iterative(m: i64) -> i64 {
    let mut total = 0;
    let mut n: i64 = 0;

    while total < m {
        n += 1;
        total += n.pow(3)
    }

    if total == m {
        n
    } else {
        0
    }
}

Formula:

pub fn pile_of_cubes_formula(m: i64) -> i64 {
    let n = ((8.0 * (m as f64).sqrt() + 1.0).sqrt() - 1.0) / 2.0;
    if n == n.floor() {
        n.floor() as i64
    } else {
        0
    }
}

And a little benchmark (with the number 91716553919377 from the examples):

test tests::pile_of_cubes::bench_formula   ... bench:          34 ns/iter (+/- 2)
test tests::pile_of_cubes::bench_iterative ... bench:       9,900 ns/iter (+/- 20)

Formula is ~290 times faster than the iterative method (for me; your numbers may vary!)


A bit of related info: I published my solutions to daily challenges (in Rust) on GitHub - currently days 43-55, but I plan to expand on that :)