Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python function to check if number is prime [duplicate]

Tags:

python

def is_prime(num):
    lst = []
    if num > 1:
        pass
    else:
        return False
    for number in range(0, 1000000+1):
        if str(num) in str(number):
            continue
        elif str(1) in str(number):
            continue
        elif str(0) in str(number):
            continue
        lst.append(number)
    for x in lst:
        if num % num == 0 and num % 1 == 0 and not(num % x == 0):
            return True
        else:
            return False

print(is_prime(9))

I do not know what is the problem with my code and I cannot find a solution the point of the program is to check whether the number is a prime number or not(prime number is only divisible by 1 and itself). The for loop just doesn't seem to work or something

like image 669
Irkl1_ Avatar asked Mar 20 '26 17:03

Irkl1_


1 Answers

def isprime(n):
    return (all([False for i in range(2,n) if n % i == 0 ]) and not n < 2)
    
print (isprime(0))
print (isprime(1))
print (isprime(2))
print (isprime(3))
print (isprime(9))
print (isprime(10))
print (isprime(13))

Output:

False
False
True
True
False
False
True

Or:

def isprime(n):

    if n < 2: return False

    for i in range(2, n):
        if n % i == 0:
            return False
    else:
        return True
like image 164
Synthase Avatar answered Mar 23 '26 07:03

Synthase



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!