简体   繁体   中英

Python prime number list wrong?

I've tried with several different methods to get the 10001 prime number.

def isPrime(value):
  if ((2**value)-2)%value==0:
    return True

def nthPrime(n):
  count = 0
  value = 1
  while count < n:
    value += 1
    if isPrime(value):
      count += 1
  return value

When 10001 is the argument this returns 103903. When I'm expecting 104743.

I've tried:

primes = []
for i in range(2,105000):
  if ((2**i) - 2) % i == 0:
    primes.append(i)

print primes[10001] ---> 103903

I believe your prime sieve is wrong. Try using an isPrime function that takes that number mod each lesser prime. If any of these are 0 then the number is composite (not prime). To the best of my knowledge there is no single comparison that will tell you if a number is prime, as your isPrime function assumes.

Is this for Project Euler? It does seem familiar to me.

Your isPrime function is wrong, like TEOUltimus said, there is no one way to tell if a number is prime.

Simple Prime Generator in Python

This pretty much answers your question i guess.

You can make a function to generate primes, this might be slow but it will work.

Here's my function to do so :

def PrimesSieve(limit):
    np=set()
    p=[2]
    for i in xrange(1,limit+1,2):
            if i == 1: continue
            if {i} & np: continue
            beg=2 if i % 2 == 0 else 0
            for j in xrange(beg,int(limit)+1,i):
                    np.add(j)
            p.append(i)
    return p

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM