Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Computes the Collatz sequence for a given integer [Mu: Python 3]
- # Copyright 2022, 2023 Roland Richter
- # The Collatz sequence is defined as follows:
- # * choose an arbitrary positive integer as the starting number
- # * then
- # - if the number is even, divide it by two,
- # - if the number is odd, triple it and add one.
- # * repeat the computation until the number 1 is reached
- #
- # see https://en.wikipedia.org/wiki/Collatz_conjecture
- # return True if z is even, False otherwise
- def is_even(z):
- return z % 2 == 0 # "==" means comparison: lhs equals rhs?
- # compute the next Collatz number, as defined above
- def next_collatz(n):
- if is_even(n):
- return n//2 # use integer division!
- else:
- return 3*n+1
- inp = input("Enter an integer number: ")
- # If the user entered something, try to convert it to a number,
- # and do Collatz computations for this starting number.
- if inp:
- startnum = int(inp) # convert string to integer
- num = startnum
- nums = []
- step = 0
- while (num > 1):
- print("Step", step, ":", num)
- # First, keep track of the current number, ...
- nums.append(num)
- # ... then, compute the next step, and the next number.
- # Python allows to assign two (or more) values to two
- # (or more) variables in one line
- step, num = step+1, next_collatz(num)
- # After the loop is finished, print the number one last
- # time, then print an "The End" text.
- print("Step", step, ":", num)
- print("The sequence started with", nums[0], "and ends after", step, "steps")
- print("The largest number was", max(nums))
- # ----------------------------------------------------------------------
- # This program is free software: you can redistribute it and/or modify
- # it under the terms of the GNU General Public License as published by
- # the Free Software Foundation, either version 3 of the License, or
- # (at your option) any later version.
- #
- # This program is distributed in the hope that it will be useful,
- # but WITHOUT ANY WARRANTY; without even the implied warranty of
- # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- # GNU General Public License for more details.
- #
- # You should have received a copy of the GNU General Public License
- # along with this program. If not, see <https://www.gnu.org/licenses/>.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement