Created
March 22, 2018 22:24
-
-
Save henninglive/2f0c028569622adde797651e7717171a to your computer and use it in GitHub Desktop.
Calculate sum of range with step in constant time
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use std::ops::Range; | |
| fn sum_range2(range: Range<usize>, step: usize) -> usize { | |
| assert!(range.start < range.end && step > 0); | |
| let mut start = range.start; | |
| while start % step != 0 { | |
| start += 1; | |
| } | |
| let mut end = range.end - 1; | |
| while end % step != 0 { | |
| end -= 1; | |
| } | |
| start = (start / step) - 1; | |
| end = (end / step); | |
| let sum_start = (start * (start + 1)) / 2; | |
| let sum_end = (end * (end + 1)) / 2; | |
| (sum_end - sum_start) * step | |
| } | |
| fn sum_range1(range: Range<usize>, step: usize) -> usize { | |
| assert!(range.start < range.end && step > 0); | |
| range.filter(|i| i % step == 0).sum() | |
| } | |
| fn main() { | |
| println!("sum_range1: {}", sum_range1(1_000_000..2_000_000, 3)); | |
| println!("sum_range3: {}", sum_range2(1_000_000..2_000_000, 3)); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment