-2

snap shot for code the python program to check prime number in list of number consider 55 and 25 as prime number which is actually not prime because 55/5=11 and reminder is zero so what problem in code

def check_prime(n):
    for i in range(2,n,1):
        if(n%i)==0:
            return  1
        else :
            return 0

numbers=[51,52,53,54,55,13,407,508,11,17,60,12,19,25,30,]
for j in numbers:
    if check_prime(j)==1:
        print("the {} is not prime".format(j))
    else:
        print("th {} is prime".format(j))
  • Can you please past your code here? – Taohidul Islam Apr 23 '20 at 18:19
  • May I suggest flipping the return values? It has nothing to do with your issue, but if you see the function name check_prime as a question of "is this a prime number?", then you'd prefer a return value of 1 to be yes and 0 to be no. – Kroshtan Apr 23 '20 at 18:28

4 Answers4

0

because, you put return in your function, and for this reason your function only do the first evaluation in other your function only return if a number is odd or ever, because only evaluate when i = 2, your function has to be.

def check_prime(n):
   for i in range(2,n):
      if(n%i)==0:return False
   return True
Sho_Lee
  • 149
  • 4
0

You have a logical error in check_prime function, try this :

def check_prime(n):
    for i in range(2, n, 1):
        if (n % i) == 0:
            return True
    return False


numbers = [51, 52, 53, 54, 55, 13, 407, 508, 11, 17, 60, 12, 19, 25, 30, ]
for j in numbers:
    if check_prime(j):
        print("the {} is not prime".format(j))
    else:
        print("th {} is prime".format(j))
Taohidul Islam
  • 5,246
  • 3
  • 26
  • 39
0

Your function returns after a single iteration, cancelling the effect of your for loop. You want to return when finding its not a prime number, but you need to continue looping through all numbers before you can say a prime number is prime. Also, flipped the return values to make more intuitive sense.

def check_prime(n):
    for i in range(2,n,1):
        if(n%i)==0:
            return  0
    return 1
Kroshtan
  • 637
  • 5
  • 17
0

You need to make the return in your loop conditional. It will exit after a single loop in this case, which is why you are seeing it return false positives.