Skip to content

Instantly share code, notes, and snippets.

@graue graue/collatz.rs
Created Jun 2, 2014

Embed
What would you like to do?
// 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
You can’t perform that action at this time.