Skip to content

Instantly share code, notes, and snippets.

@graue
Created June 2, 2014 06:50
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 graue/dee41328ee341894467f to your computer and use it in GitHub Desktop.
Save graue/dee41328ee341894467f to your computer and use it in GitHub Desktop.
// Prints Collatz sequence from a given integer.
// By Scott Feeney, released under CC0 Public Domain Dedication 1.0.
use std::io;
fn main() {
let mut num = read_number();
loop {
println!("{:d}", num);
match next_collatz(num) {
Some(next) => { num = next; }
None => { break; }
}
}
}
fn next_collatz(n: int) -> Option<int> {
if n <= 1 { None }
else if n % 2 == 0 { Some(n / 2) }
else { Some(3*n + 1) }
}
fn chomp<'a>(s: &'a str) -> &'a str {
s.trim_right_chars('\n')
}
fn read_number() -> int {
loop {
print!("Enter an integer: ");
let val = io::stdin().read_line().ok().and_then(|s| {
from_str(chomp(s.as_slice()))
});
match val {
Some(number) => { return number },
None => { println!("That isn't a valid integer!") }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment