I am attempting to use a prime sieve to find all the prime factors of certain numbers. In my code, I end up having to divide a very large number by a small number to find a prime factor that is out of the range of the sieve I'm using. This shouldn't be a problem, in fact, the method works perfectly for every number I checked except for one.
The problem I have run into is that I divide this large number by 51 to find the prime factor and then when I multiply it by 51 to check if it equals the original number... IT DOESN'T!!
It does not work regardless of if I convert it to an int or if I leave it as a float in scientific notation.
I understand that floats are not perfect, but I don't know how to get around this weird error. I even plugged the numbers into a calculator and got the correct answer, but my code gives me the wrong answer.
What is going on here? If you run my code you will see that the checks return False when they should be True for both.
As I said before, this method WORKS for one of the numbers I am testing that has a factor outside the range of the sieve I am using, it is only this specific large number that I am having issues with.
The correct answer should be 1,176,462,117,668,023,508,828,242,241 and the answer im getting is 1,176,462,117,668,023,481,334,235,136
l_number = 59999568001069198950240354291
answer = 59999568001069198950240354291 / 51
int_answer = int(answer)
check = int_answer*51
check2 = answer * 51
print("The large number is: {:,d}".format(l_number))
print("Large number divided by 51: ", answer)
print("If the check is == original number: ", check2 == 59999568001069198950240354291)
print("Large number divided by 51 as an integer: {:,d}".format(int_answer))
print("That answer * 51 (should be original number): {:,d}".format(check))
print("If the integer check is == original number: ", check == 59999568001069198950240354291)
As you point out float division is not exact due to the limited precision available to a 64-bit double.
It works if you use integer division (in Python 3)
answer = 59999568001069198950240354291 // 51
This works because Python uses arbitrary precision integer arithmetic.