The question asks for the prime number from 1-25 and this is my code, it came out to be wrong. Can anyone help me plz???Thank you so much!
n=1
f=0
while n<=25:
for i in range(2,n):
if n%i==0:
f+=1
else:
f
if f==0:
print str(n) + "is a prime number"
else:
print str(n) + "is not a prime number"
n+=1
You are not re-setting the value of f
, so once you hit a non-prime number all the numbers following that will be reported as not prime.
n=1
f=0
while n<=25:
for i in range(2,n):
if n%i==0:
f+=1
else:
f
if f==0:
print str(n) + "is a prime number"
else:
print str(n) + "is not a prime number"
f = 0
n+=1
Also your way is inefficient, and you should start from 2, not 1. Also, all the prime numbers after 3 are of the form of 6n-1 or 6n+1 (Where n is a integer). So you do not need to test all the numbers. Just test the numbers 6n-1 and 6n+1 if they are prime or not.
I've re-arranged your code to make it a little more efficient. It first tests if n
is even, and then it tests for odd factors up to the square root of n
, since if n
is not prime it must have a factor <= its square root. (Can you see why?)
To simplify the logic, I've moved the testing into a function.
When a factor of n
is found we immediately return from the function since there's no point looking for more factors.
def prime_test(n):
if n % 2 == 0:
return False
for i in range(3, int(n**0.5 + 1), 2):
if n % i == 0:
return False
return True
print 2, "is a prime number"
for n in range(3, 26):
if prime_test(n):
print n, "is a prime number"
else:
print n, "is not a prime number"
output
2 is a prime number
3 is a prime number
4 is not a prime number
5 is a prime number
6 is not a prime number
7 is a prime number
8 is not a prime number
9 is not a prime number
10 is not a prime number
11 is a prime number
12 is not a prime number
13 is a prime number
14 is not a prime number
15 is not a prime number
16 is not a prime number
17 is a prime number
18 is not a prime number
19 is a prime number
20 is not a prime number
21 is not a prime number
22 is not a prime number
23 is a prime number
24 is not a prime number
25 is not a prime number
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.