0

So I got this Python code where it should give me the amount of steps for each number when we apply the Collatz algorithm on it.

When I input small integers, it gives the correct amount of steps. But when I input large numbers, it gives me the wrong number of steps.

Here's a code that reproduces the same thing:

import math

number = 931386509544713451 # Number here

def collatz_algorithm(n):
    x = math.floor(n)
    A_N = 0
    while x != 1:
        if x % 2 == 0:
            x = x / 2
        else:
            x = 3*x + 1
        A_N += 1
    print("\nNumber of steps for {}: {}".format(str(n),str(A_N)))
 
collatz_algorithm(number)

When you input small numbers such as 7, it does just fine and it gives the right number of steps. But when you input a large number as 931386509544713451, it gives the wrong number of steps (As shown in the Wiki here: https://en.wikipedia.org/wiki/Collatz_conjecture)

I tried to do many things, such as converting to ulonglong with ctypes but still didn't work, I was thinking it could increase the number limit, but it didn't.

So could anyone help?

wjandrea
  • 28,235
  • 9
  • 60
  • 81

1 Answers1

3

x = x / 2 is converting your number to a float which is imprecise. Replace it with x = x // 2 so that integer division will be used.

Output (matches Wikipedia):

Number of steps for 931386509544713451: 2283
Random Davis
  • 6,662
  • 4
  • 14
  • 24