From f9a42d16e7b763c7feb28cd11146a2e9a2e4c822 Mon Sep 17 00:00:00 2001 From: Muhammad Nauman Raza Date: Wed, 20 Nov 2024 22:30:45 +0000 Subject: [PATCH] solutions: 14 --- longest_collatz_sequence.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 longest_collatz_sequence.rs diff --git a/longest_collatz_sequence.rs b/longest_collatz_sequence.rs new file mode 100644 index 0000000..4d2dfb1 --- /dev/null +++ b/longest_collatz_sequence.rs @@ -0,0 +1,33 @@ +fn collatz_sequence(starting_num: u64) -> Vec { + let mut num = starting_num; + let mut result: Vec = vec![]; + + result.push(num); + + while num != 1 { + if num % 2 == 0 { + num /= 2; + result.push(num); + } else { + num = (3*num)+1; + result.push(num); + } + } + + result +} + +fn main() { + let mut increment: u64 = 0; + let mut longest: u64 = 0; + + for i in 1..=1000000 { + let length = collatz_sequence(i).len() as u64; + if length > longest { + longest = length; + increment = i; + } + } + + println!("{:?}", increment); +}