Last active
          April 16, 2024 15:41 
        
      - 
      
- 
        Save kehiy/ac8f48496d374f73f4fdcec5538bbf41 to your computer and use it in GitHub Desktop. 
    Collatz conjecture or 3n+1 problem in python
  
        
  
    
      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
    
  
  
    
  | import random | |
| def is_odd(num: int): | |
| if (num % 2) == 0: | |
| return False | |
| return True | |
| def collatz(num: int): | |
| if num == 1: | |
| print("its one!") | |
| exit(0) | |
| if is_odd(num): | |
| new_num = num * 3 + 1 | |
| print(new_num) | |
| collatz(new_num) | |
| new_num = num / 2 | |
| print(new_num) | |
| collatz(new_num) | |
| collatz(random.randint(3, 10)) # you can use any number or rage you want. I used 3 as minimum, so you can see the 4, 2, 1 result. I used 10 as maximum to make sure it will run fast and easy. | |
| # you can give this function any number, and regarding to 3n + 1 problem it will end with 4, 2, 1 numbers always. | |
| # read this for more informtation: | |
| # https://en.wikipedia.org/wiki/Collatz_conjecture | |
| # this youtube video is a more fluent explanition of this: | |
| # https://www.youtube.com/watch?v=094y1Z2wpJg | 
  
    
      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
    
  
  
    
  | fn is_odd(num: usize) -> bool { | |
| return (num % 2) != 0 | |
| } | |
| fn collatz(num: usize) { | |
| if num == 1 { | |
| println!("it's one!"); | |
| return; | |
| } | |
| if is_odd(num) { | |
| let new_num = num * 3 + 1; | |
| println!("{}", new_num); | |
| collatz(new_num); | |
| return; | |
| } | |
| let new_num = num / 2; | |
| println!("{}", new_num); | |
| collatz(new_num); | |
| return; | |
| } | |
| fn main() { | |
| collatz(7) | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment