Wednesday, June 23, 2010

Project Euler: Problem 7

http://projecteuler.net/index.php?section=problems&id=7

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the 10001st prime number?

To my knowledge, there aren't any good (efficient) know methods of generating primes. This leaves only quasi-brute force methods. We'll keep iterating our test index (by 2 to only check odd numbers) and check for primeness.

def f1(n):
    # Define test for primeness
    def isprime(x):
        if x <= 1: return False

        c = 2

        while c <= x**0.5:
            if x%c == 0:
                return False

            if c != 2:
                c += 2
            else:
                c += 1

        return True

    # Iterate over odd numbers and test for primeness
    count = 1
    i = 1

    # Stop when we've found n primes
    while count < n:
        i += 2
        if isprime(i):
            count += 1

    # Return the last found prime
    return i

This obviously isn't very good, but it does return the 10001st prime in about 0.8 seconds.

No comments:

Post a Comment