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.
The problem occurs in this line:
You could use the periodicity of cos(1π) = cos(3π) etc. and analogously for the even multiples of pi. So subtract all multiples of 2π (360°) from the argument, (factorial(j - 1) + 1) / j before calculating cos.