Skip to content

Commit

Permalink
https://exercism.org/tracks/rust/exercises/collatz-conjecture
Browse files Browse the repository at this point in the history
  • Loading branch information
hyunjun committed Feb 29, 2024
1 parent 00b6d64 commit a9a3c29
Show file tree
Hide file tree
Showing 3 changed files with 80 additions and 0 deletions.
4 changes: 4 additions & 0 deletions rust/collatz-conjecture/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[package]
edition = "2021"
name = "collatz_conjecture"
version = "1.2.1"
32 changes: 32 additions & 0 deletions rust/collatz-conjecture/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
pub fn collatz_recur(count: u64, n: u64) -> Option<u64> {
match n {
1 => Some(count),
_ => collatz_recur(count + 1, if n % 2 == 0 { n / 2 } else { 3 * n + 1 })
}
}
pub fn collatz(n: u64) -> Option<u64> {
if n < 1 {
return None;
}
//collatz_recur(0, n)
let mut num = n;
let mut count = 0;
while num != 1 {
println!("{} {}", num, count);
count += 1;
if num % 2 == 0 {
num = num / 2;
} else {
let (multiplied, is_overflowed) = num.overflowing_mul(3);
if is_overflowed {
return None;
}
let (added, is_overflowed) = multiplied.overflowing_add(1);
if is_overflowed {
return None;
}
num = added;
}
}
Some(count)
}
44 changes: 44 additions & 0 deletions rust/collatz-conjecture/tests/collatz-conjecture.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
use collatz_conjecture::*;

#[test]
fn one() {
assert_eq!(Some(0), collatz(1));
}

#[test]
fn sixteen() {
assert_eq!(Some(4), collatz(16));
}

#[test]
fn twelve() {
assert_eq!(Some(9), collatz(12));
}

#[test]
fn one_million() {
assert_eq!(Some(152), collatz(1_000_000));
}

#[test]
fn zero() {
assert_eq!(None, collatz(0));
}

#[test]
fn test_110243094271() {
let val = 110243094271;
assert_eq!(None, collatz(val));
}

#[test]
fn max_div_3() {
let max = u64::MAX / 3;
assert_eq!(None, collatz(max));
}

#[test]
fn max_minus_1() {
let max = u64::MAX - 1;
assert_eq!(None, collatz(max));
}

0 comments on commit a9a3c29

Please sign in to comment.