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):
91716553919377
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 :)
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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:
Formula:
And a little benchmark (with the number
91716553919377
from the examples):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 :)