summaryrefslogtreecommitdiff
path: root/rust
diff options
context:
space:
mode:
Diffstat (limited to 'rust')
-rw-r--r--rust/collatz-conjecture/README.md2
-rw-r--r--rust/collatz-conjecture/src/lib.rs15
-rw-r--r--rust/collatz-conjecture/tests/collatz-conjecture.rs4
3 files changed, 15 insertions, 6 deletions
diff --git a/rust/collatz-conjecture/README.md b/rust/collatz-conjecture/README.md
index 0f2232a..8488385 100644
--- a/rust/collatz-conjecture/README.md
+++ b/rust/collatz-conjecture/README.md
@@ -56,4 +56,4 @@ So for input n = 12, the return value would be 9.
### Based on
-An unsolved problem in mathematics named after mathematician Lothar Collatz - https://en.wikipedia.org/wiki/3x_%2B_1_problem \ No newline at end of file
+An unsolved problem in mathematics named after mathematician Lothar Collatz - https://en.wikipedia.org/wiki/3x_%2B_1_problem
diff --git a/rust/collatz-conjecture/src/lib.rs b/rust/collatz-conjecture/src/lib.rs
index 84f1782..6642ab1 100644
--- a/rust/collatz-conjecture/src/lib.rs
+++ b/rust/collatz-conjecture/src/lib.rs
@@ -1,3 +1,16 @@
+fn next(n: u64) -> u64 {
+ if n%2 == 0 { n/2 } else { 3*n+1 }
+}
+
pub fn collatz(n: u64) -> Option<u64> {
- todo!("return Some(x) where x is the number of steps required to reach 1 starting with {n}")
+ if n == 0 {
+ return None
+ }
+ let mut count = 0;
+ let mut x = n;
+ while x != 1 {
+ x = next(x);
+ count += 1;
+ }
+ Some(count)
}
diff --git a/rust/collatz-conjecture/tests/collatz-conjecture.rs b/rust/collatz-conjecture/tests/collatz-conjecture.rs
index 9bbced3..8e5edf0 100644
--- a/rust/collatz-conjecture/tests/collatz-conjecture.rs
+++ b/rust/collatz-conjecture/tests/collatz-conjecture.rs
@@ -9,7 +9,6 @@ fn zero_steps_for_one() {
}
#[test]
-#[ignore]
fn divide_if_even() {
let output = collatz(16);
@@ -18,7 +17,6 @@ fn divide_if_even() {
}
#[test]
-#[ignore]
fn even_and_odd_steps() {
let output = collatz(12);
@@ -27,7 +25,6 @@ fn even_and_odd_steps() {
}
#[test]
-#[ignore]
fn large_number_of_even_and_odd_steps() {
let output = collatz(1000000);
@@ -36,7 +33,6 @@ fn large_number_of_even_and_odd_steps() {
}
#[test]
-#[ignore]
fn zero_is_an_error() {
let output = collatz(0);