-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrait.rs
More file actions
37 lines (28 loc) · 690 Bytes
/
Copy pathtrait.rs
File metadata and controls
37 lines (28 loc) · 690 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
use std::time::Instant;
fn main() {
let finder = OddFinderOne;
let start_time = Instant::now();
let result = find_nth_odd(finder, 1_000_000_000);
let elapsed_time = start_time.elapsed().as_millis();
println!("{} in {} ms", result, elapsed_time);
}
fn find_nth_odd(odd_finder: OddFinderOne, n: u64) -> u64 {
let mut i = 0;
let mut odd_count = 0;
while odd_count != n {
i += 1;
if odd_finder.is_odd(i) {
odd_count += 1;
}
}
i
}
trait OddFinder {
fn is_odd(&self, n: u64) -> bool;
}
struct OddFinderOne;
impl OddFinder for OddFinderOne {
fn is_odd(&self, n: u64) -> bool {
n % 2 == 1
}
}