Skip to content

Instantly share code, notes, and snippets.

@cristianoliveira
Last active March 28, 2021 22:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cristianoliveira/730e4d3ea2991975b8bf to your computer and use it in GitHub Desktop.
Save cristianoliveira/730e4d3ea2991975b8bf to your computer and use it in GitHub Desktop.
Collatz Conjecture in Rust
// 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);
}
@Titaniumtown
Copy link

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment