-4

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.

2
  • 1
    Your factorial() result exceeds 1.7976931348623157e+308; hence the error as this is the maximum float value. Commented Jan 29, 2024 at 14:33
  • math formulas are not necessarily aimed at efficient computation. For example, this one is not. Commented Jan 29, 2024 at 17:02

1 Answer 1

0

The problem occurs in this line:

floor(pow(cos(pi * (factorial(j - 1) + 1) / j)

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.