I wrote a prime generating code in Python, and it produces correct results. However when i want to print 8th prime I get an OverflowError:
sum += floor(pow(cos(pi * (factorial(j - 1) + 1) / j), 2))
OverflowError: int too large to convert to float
I tried to use decimal module, but I cant fix the problem.
Code:
from math import floor, cos, pi, factorial
def nth_prime(n):
if isinstance(n, int) and n > 0:
end_sum = 0
for i in range(1, 2 ** n + 1):
sum = 0
for j in range(1, i + 1):
sum += floor(pow(cos(pi * (factorial(j - 1) + 1) / j), 2))
end_sum += floor(pow((n / sum), (1 / n)))
return end_sum + 1
else:
raise Exception("Enter a positive integer")
print(nth_prime(8))
I tried using decimal module, but I don't know how to use it.
factorial()result exceeds 1.7976931348623157e+308; hence the error as this is the maximum float value.