finish 14

This commit is contained in:
Dr. Matthias Ratajczak
2022-08-19 14:56:24 +02:00
parent eb369c54c8
commit a14f7f1fd4
2 changed files with 61 additions and 0 deletions
+8
View File
@@ -0,0 +1,8 @@
[package]
name = "euler14"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
+53
View File
@@ -0,0 +1,53 @@
fn main() {
let mut starts_longest = 0;
let mut max_length = 0;
for i in 1..1_000_000 {
let length = Collatz::new(i).count();
if length > max_length {
max_length = length;
starts_longest = i;
}
}
println!("{starts_longest}");
}
struct Collatz {
n: usize,
done: bool,
}
impl Collatz {
fn new(n: usize) -> Self {
Self { n, done: false }
}
}
impl Iterator for Collatz {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
if self.done {
return None;
}
if self.n == 1 {
self.done = true;
return Some(self.n);
}
if self.n % 2 == 0 {
self.n /= 2
} else {
self.n = 3 * self.n + 1;
}
Some(self.n)
}
}
#[cfg(test)]
mod test {
use super::Collatz;
#[test]
fn collatz() {
assert_eq!(Collatz::new(13).count(), 10);
}
}