1

I am writing a program for Project Euler question 7 that attempts to find the 10001st prime. I adapted a script I already had that found all primes up to any number. It worked fine. But now I have a problem. My code repeats the list.

881, 883, 887, 1, 2, 3, 5, 7, 11, 13, 17, 19

that is from roughly the middle of my code.

max = int(input("What is your max no?: "))
primeList = []

while len(primeList) <= 10001:
for x in range(1, max + 1):
    isPrime = True
    for y in range (2 , int(x ** 0.5) + 1):
        if x % y == 0:
            isPrime = False
            break

    if isPrime:
        primeList.append(x)


print(primeList)

What is causing this? Should I start from a blank canvas and not edit an old script?

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Einstein.py
  • 61
  • 1
  • 9

2 Answers2

1

For the fun of it I also solved the problem:

# Test only odd numbers because we know the only even prime is 2
oddprimes = [3]
n = 3
# when we have 10000 oddprimes we will have a total of 10001 primes: [2] + oddprimes
while len(oddprimes) < 10000:
    n += 2 # advance to the next odd number
    maxfactor = int(n ** 0.5) + 1
    # only need to check prime factors
    for prime in oddprimes:
        if n % prime == 0:
            # it's not prime, stop looking
            break 
        elif prime >= maxfactor:
            # if we're checking prime factors >= sqrt(n)+1 then it's prime
            oddprimes.append(n) 
            break

print oddprimes[-1] # the 10000th odd prime which is the 10001st prime
Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119
0

Each time you find a prime nuember you are adding it to the primeList, so the last line is being asked to print a list. If you want the final element you can just:

print primeList[-1]
patito
  • 530
  • 2
  • 13