I have just begun to learn python, so my question is probably silly. Just for practice I want to write a function which calculates the first n primes. prime computes some prime numbers and keeps them in a list. Then tries another number and if it's not even divisible by the already discovered numbers then adds it in the list. But unfortunately, as you may already have guessed, it doesn't work.

``````from math import sqrt
from math import floor

def prime(n):
primes = []
# how many prime number have been discovered
i = 3
# the list of them
primes.append(1)
primes.append(2)
primes.append(3)
# the last prime number
a = 3
while i < n:
# the next prime candidate
a = a + 2
for j in range(i):
# if it isn't prime, search for another
if floor(sqrt(a)) < primes[j] or a % primes[j] == 0:
break
### this condition is never true. Why?
if j >= i - 1 or floor(sqrt(a)) < primes[j]:
primes.append(a)
i += 1
print i

return primes

result = prime(10)
print result[-1]``````

Problem solved. The problem is line 9 and is solved if it is removed because all natural numbers can be divided by 1.

A more elegant solution:

``````from math import sqrt
from math import floor

def prime(n):
primes = []
# how many prime number have been discovered
i = 3
# the list of them
primes.append(2)
primes.append(3)
# the last prime number
a = 3
is_prime = 0
while i < n:
# look for the next prime
a += 2
for j in primes:
if j <= floor(sqrt(a)):
if a % j == 0:
is_prime = 0
break
else:
is_prime = 1
break
if is_prime == 1:
primes.append(a)
i += 1

return primes

result = prime(20)
print result``````
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.