Project Euler – Problem # 7 – Solved with Java & Python

Find the 10001st prime.

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 10 001st prime number?

One Possible Solution: Java


public class Problem_07 {
	public static void main(String args[])
	{
		Problem_07 prob_07Obj = new Problem_07();
		int Switch = 1;
		int counter = 1;
		int primes = 0;
		while(Switch == 1){
			if (prob_07Obj.isPrime(counter)){
				primes += 1;
				counter += 2;
			} else
			{
				counter += 2;
			}
			if (primes == 10001){
				System.out.println(counter - 2);
				Switch = 0;
			}
		}
		
	}
	public boolean isPrime(int n)
    {
    int k = (int) Math.sqrt(n);
            for (int i = 2; i <= k; i++)
            {
                    if (n % i == 0)
                            return false;
            }
            return true;
    }
}

One Possible Solution: Python

# Python version 2.7.2
# Platform = win32

def isprime(n):
    """Checks number (n) for primality, and returns
    True of False."""
    n = abs(int(n))
    if n < 2:
        return False
    if n == 2:
        return True
    if not n & 1:
        return False
    for x in range(3, int(n ** 0.5) + 1, 2):
        if n % x == 0:
            return False
    return True 

def main():
    """this example takes the numbers 1, 3, 5, 7, 9, etc., and
    checks for primality."""
    Switch = 1
    number = 1
    primes = 1 # start with 1 since we do not count 2, which is a prime
    while Switch == 1:
        if isprime(number):
            primes += 1 
        if primes == 10001: # Stop at 10001, and print that number
            print number
            Switch = 0
        number += 2

if __name__ == '__main__':
    main()
Advertisements

1 Comment

  1. def isPrime(num):
    primecount = 1
    count = 1
    while count 2):
    return False
    break
    count += 1
    return True

    >>> def foundPrime():
    primecount = 0
    count = 1
    limit = 10001
    while (primecount < limit):
    if (isPrime(count)):
    primecount += 1
    count += 1
    else:
    count += 1
    return count

    Hello, what seems to be wrong in my code?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s