Last active
March 28, 2021 22:08
-
-
Save cristianoliveira/730e4d3ea2991975b8bf to your computer and use it in GitHub Desktop.
Collatz Conjecture in Rust
This file contains 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
// Responsible for calcule Collatz Conjecture | |
// n -> n/2 (if n is pair) n -> 3n + 1 (if n is odd) | |
// | |
fn calcule(num: u64) -> u64 { | |
if num <= 1 { return 1; }; | |
if num % 2 == 0 { | |
num / 2 | |
} else{ | |
3 * num + 1 | |
} | |
} | |
fn collatz(num: u64, step: u64) -> u64 { | |
let res = calcule(num); | |
if res == 1 { | |
step + 1 | |
} else { | |
collatz(res, step + 1) | |
} | |
} | |
fn main() { | |
let mut max_num: u64 = 0; | |
let mut max_steps: u64 = 0; | |
for i in 1..1000000 { | |
let steps = collatz(i, 1); | |
if max_steps < steps { | |
max_steps = steps; | |
max_num = i; | |
} | |
} | |
println!("Result num: {} in {} steps", max_num, max_steps); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!