Advertisement
rric

halt_at_number_one

Oct 30th, 2023 (edited)
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.34 KB | None | 0 0
  1. # Computes the Collatz sequence for a given integer [Mu: Python 3]
  2. # Copyright 2022, 2023 Roland Richter
  3.  
  4. # The Collatz sequence is defined as follows:
  5. # * choose an arbitrary positive integer as the starting number
  6. # * then
  7. #   - if the number is even, divide it by two,
  8. #   - if the number is odd, triple it and add one.
  9. # * repeat the computation until the number 1 is reached
  10. #
  11. # see https://en.wikipedia.org/wiki/Collatz_conjecture
  12.  
  13. # return True if z is even, False otherwise
  14. def is_even(z):
  15.     return z % 2 == 0   # "==" means comparison: lhs equals rhs?
  16.  
  17. # compute the next Collatz number, as defined above
  18. def next_collatz(n):
  19.     if is_even(n):
  20.         return n//2   # use integer division!
  21.     else:
  22.         return 3*n+1
  23.  
  24. inp = input("Enter an integer number: ")
  25.  
  26. # If the user entered something, try to convert it to a number,
  27. # and do Collatz computations for this starting number.
  28. if inp:
  29.     startnum = int(inp)   # convert string to integer
  30.  
  31.     num = startnum
  32.     nums = []
  33.     step = 0
  34.  
  35.     while (num > 1):
  36.         print("Step", step, ":", num)
  37.  
  38.         # First, keep track of the current number, ...
  39.         nums.append(num)
  40.  
  41.         # ... then, compute the next step, and the next number.
  42.         # Python allows to assign two (or more) values to two
  43.         # (or more) variables in one line
  44.         step, num = step+1, next_collatz(num)
  45.  
  46.     # After the loop is finished, print the number one last
  47.     # time, then print an "The End" text.
  48.     print("Step", step, ":", num)
  49.     print("The sequence started with", nums[0], "and ends after", step, "steps")
  50.     print("The largest number was", max(nums))
  51.  
  52. # ----------------------------------------------------------------------
  53. # This program is free software: you can redistribute it and/or modify
  54. # it under the terms of the GNU General Public License as published by
  55. # the Free Software Foundation, either version 3 of the License, or
  56. # (at your option) any later version.
  57. #
  58. # This program is distributed in the hope that it will be useful,
  59. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  60. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  61. # GNU General Public License for more details.
  62. #
  63. # You should have received a copy of the GNU General Public License
  64. # along with this program.  If not, see <https://www.gnu.org/licenses/>.
  65.  
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement