Created
June 2, 2014 06:50
-
-
Save graue/dee41328ee341894467f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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