How do you find the first N prime numbers in python?
How do you find the first N prime numbers in python?
I am pretty new to python, so I don't fully understand how to use loops. I am currently working on a piece of code that I have to find the first N prime numbers.
The result that is desired is if you input 5, it outputs 2, 3, 5, 7, and 11, but no matter what I input for 'max', the output always ends up being 2 and 3. Is there a way to improve this?
max=int(input("How many prime numbers do you want: "))
min=2
while(min<=(max)):
for c in range(2, min):
if min%c==0:
break
else:
print min
min=min+1
This is a side comment. If you are new to Python I would strongly recommend jumping on 3.x Python (3.6 is stable release) as 2.7 will be deprecated in a few years.
– Anton vBR
Jun 30 at 18:28
Note that
min
and max
are builtin functions of Python. You should avoid using these names for your variables, as their values would replace the original function. Trying to execute min(2, 3)
after your code would cause a TypeError: 'int' object is not callable
– Thierry Lathuille
Jun 30 at 18:31
min
max
min(2, 3)
TypeError: 'int' object is not callable
3 Answers
3
You only increment min
in the else
block, i.e., if min % c
is nonzero for all c
, i.e., if min
is prime. This means that the code won't be able to move past any composite numbers. You can fix this by unindenting min=min+1
one level so that it lines up with the for
and else
.
min
else
min % c
c
min
min=min+1
for
else
I guess this will help, let me know.
number = int(input("How many prime numbers do you want ? "))
cnt = 0
for i in range (1, number+1):
for j in range(1, i+1):
if(i%j == 0):
cnt += 1
if(cnt == 2):
print(i)
cnt = 0
number = int(input("Prime numbers between 2 and "))
for num in range(2,number + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
You don't really want 10 prime numbers then, just the prime numbers between 2 and 10.
– pkpkpk
Jun 30 at 18:27