Skip to content

Instantly share code, notes, and snippets.

@sarmadgulzar
Created June 10, 2022 22:49
Show Gist options
  • Save sarmadgulzar/39f748aa3707081daf2aaf0e66418638 to your computer and use it in GitHub Desktop.
Save sarmadgulzar/39f748aa3707081daf2aaf0e66418638 to your computer and use it in GitHub Desktop.
Some useful scripts to explore the 3x+1 problem explained in: https://www.youtube.com/watch?v=094y1Z2wpJg

Note: You will need to have Python 3 and Rust installed on your computer!

To check how many iterations a number takes to reach 1, run the number_of_iterations.py file as follows:

python3 number_of_iterations.py

Output:

Enter an integer: 9
9 took 19 iterations!

To check not only the number of iterations it takes for each number in a range to reach 1 but also which number takes the most iterations, run the max_iterations.rs file as follows:

Be sure to change the values of MIN and MAX which are used for the range.

rustc -O max_iterations.rs && ./max_iterations

Output:

1 took 0 iterations!
2 took 1 iterations!
3 took 7 iterations!
4 took 2 iterations!
5 took 5 iterations!
6 took 8 iterations!
7 took 16 iterations!
8 took 3 iterations!
9 took 19 iterations!
10 took 6 iterations!
Max iterations (19) by number 9!
const MIN: usize = 1;
const MAX: usize = 10;
fn is_odd(n: usize) -> bool {
n % 2 == 1
}
fn main() {
let mut max_iterations = 0;
let mut max_iterations_by_number = 0;
for i in MIN..=MAX {
let mut number = i;
print!("{} took ", number);
let mut counter = 0;
while number != 1 {
if is_odd(number) {
number = (number * 3) + 1;
} else {
number /= 2;
}
counter += 1;
}
if counter > max_iterations {
max_iterations = counter;
max_iterations_by_number = i;
}
println!("{} iterations!", counter)
}
println!(
"Max iterations ({}) by number {}!",
max_iterations, max_iterations_by_number
)
}
def get_integer() -> int:
msg = "Enter an integer: "
while True:
try:
return int(input(msg))
except Exception as _:
msg = "Please enter a valid integer: "
def is_odd(n: int) -> bool:
return n % 2 == 1
number = get_integer()
print(f"{number} took ", end="")
counter = 0
while number != 1:
if is_odd(number):
number = (number * 3) + 1
else:
number //= 2
counter += 1
print(f"{counter} iterations!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment