Home > front end >  Is there any function to directly find a number is prime or not in python?
Is there any function to directly find a number is prime or not in python?

Time:12-28

Any pre-defined Function available in Python which tells that the given number is prime or not??

I tried to find it but I think it's not there.

CodePudding user response:

You can always make your own

def check_prime(x):
fac_list = []
for i in range(1, x   1):
   if x % i == 0:
      fac_list.append(i)

return True if len(fac_list) == 2 else False

CodePudding user response:

There is no function for determining prime numbers in the standard library.

There is the possibility of using the sympy package for this. You will need to pip install sympy before using it.

import sympy
print(sympy.isprime(90))

Although, you could also write your own function for this

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

It's up to you to decide which version is better for your use case.

  • Related