0

I found something really strange happening in python with that code:

num = 99999999999999999999999999999

for i in range(2, num):
    if num % i == 0:
        j = int(num / i)
        print(num, '=', i, '*', j)
        break
else:
    print(num, 'is prime')

Python is giving me

99999999999999999999999999999 = 3 * 33333333333333333409747959808

as output, what is obviouly wrong. And as bigger num is getting, the wronger the output gets.

Can someone tell me, what's going on here?

Steve Iron
  • 241
  • 6
  • 12

1 Answers1

1

I expect you're using Python 3. In Python 3, when dividing integers with the / operator, it converts them to float and produces a float result. Floats have limited precision, so you're seeing roundoff errors.

To get integer division, without roundoff errors, you can use the // operator, which gives true integer division. Just change the assignment to j to:

j = num // i
Tom Karzes
  • 22,815
  • 2
  • 22
  • 41