Created
December 16, 2020 03:48
-
-
Save WhiteGrouse/517cc9341a5858e719780d7b65fcf4df to your computer and use it in GitHub Desktop.
Collatz Problem
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
| extern crate num_bigint; | |
| extern crate num_traits; | |
| mod utils; | |
| use num_bigint::BigUint; | |
| use utils::input_num; | |
| fn main() { | |
| let mut x = trim(input_num(10)); | |
| println!("{}, {}", x.to_str_radix(2), x); | |
| while !is_goal(&x) { | |
| // 2n + 1 to {3(2n+1)+1}/2 => 2n + n + 2 | |
| x = x - 1u64;//2n + 1 to 2n | |
| x = x.clone() + (x >> 1) + 2u64;//2n + n + 2 | |
| println!("{}, {}", x.to_str_radix(2), x); | |
| if x.trailing_zeros().unwrap() > 0 { | |
| x = trim(x); | |
| println!("{}, {} (trimmed)", x.to_str_radix(2), x); | |
| } | |
| } | |
| } | |
| fn trim(x: BigUint) -> BigUint { | |
| match x.trailing_zeros() { | |
| Some(zeros) => x >> zeros, | |
| None => x | |
| } | |
| } | |
| fn is_goal(x: &BigUint) -> bool { | |
| //x.bits() - 1 == x.trailing_zeros().unwrap() | |
| x == &1u64.into() | |
| } |
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
| use num_bigint::BigUint; | |
| use std::io::{stdin, stdout, Write}; | |
| pub fn input_num(base: u32) -> BigUint { | |
| print!("Num(base={}): ", base); | |
| stdout().flush().unwrap(); | |
| let mut line = String::new(); | |
| stdin().read_line(&mut line).unwrap(); | |
| BigUint::parse_bytes(line.trim().as_bytes(), base).unwrap() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment