finish 14
This commit is contained in:
@@ -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]
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user