+ 2
My code fails for test cases:2,3,27 can anyone help me rectify ?
Prime number or not https://code.sololearn.com/cSC5Z43IBNA0/?ref=app
23 Réponses
+ 3
There is a small mistake.
A number is prime if it's not divisible by any of the numbers less than itself.
Not if it's indivisible by just one.
Your loop breaks in just one step as it has break in both if else. For example,
n = 9
for i in range(2, n):
if n%i == 0:
print("not prime")
break
else:
print("prime")
break
Iteration 1: i = 2
9%2 == 0 is False
else part executed
"prime"
break
Hence it prints "prime" which is incorrect.
So, what to do?
We need to check if there was any case where n was divisible.
We can take help of a flag which is initially True and make it False when a divisor is encountered. So, after the end of the loop if the Flag is True - Prime and otherwise - Not prime.
n = 9
flag = True
for i in range(2, n):
if n%i == 0:
print("Not prime")
flag = False
break
if flag == True:
print("Prime")
To be continued...
+ 2
n = 9
for i in range(2, int(n/2)):
if n%i == 0:
printf("not prime")
break
else:
print("prime")
break
+ 2
Calvin Thomas thanks for reminding me
+ 1
Hi again!
num is better to be a input variable rather than a direct value. Hence, it should be an end argument for range() function.
I think these are things you have to consider. Nothing else.
num= int(input())
if num>1:
for i in range(2,num):
+ 1
Abs Sh JUMP_LINK__&&__Python__&&__JUMP_LINK Learner thank you for your suggestions
+ 1
... continuation
Luckily Python provides a better way to achieve this:
n = 9
for i in range(2, n):
if n%i == 0:
print("not prime")
break
else:
print("prime")
This is a loop-else. Here, the else part is executed only if the loop ends without break.
And about sqrt(n), it's just an optimisation. So you can replace range(2, n) with range(2, int(n**.5)+1)
+ 1
from math import sqrt
num = 10
if num == 1:
print('not prime')
elif num == 2:
print('prime')
elif num ==3:
print('prime')
else:
for i in range(2, int(sqrt(num)+1)):
print(i)
if num%i == 0:
print('not prime')
break
else:
continue
else:
print('prime')
+ 1
alagammai uma Here's a possible solution:
print("not " * (not ((n := int(input())) > 1 and all(n % i for i in range(2, n // 2 + 1)))) + "prime")
# Hope this helps
+ 1
Calvin Thomas thank you
+ 1
Atul [Inactive] This won't work for inputs lesser than 2.
+ 1
Yes Calvin Thomas that's y I asked for correction of code
+ 1
Best answer is given by Abs Sh
https://code.sololearn.com/c07G3rfyJgmM/?ref=app
+ 1
Atul [Inactive] it's correct; outputs prime!
0
For 2 and 3 it obvious int(num/2) returns 0
0
And that's not how you check a prime number
0
You get the square root of num not divide by two
0
JUMP_LINK__&&__Python__&&__JUMP_LINK Learner I respect your answer but it's not best algorithm to use for larger numbers
0
Ok JUMP_LINK__&&__Python__&&__JUMP_LINK Learner will try it out
0
here is a better answer
https://code.sololearn.com/c6ER7Nw7n8Q8/?ref=app