Example explanation of judging whether a number is a prime number in python

  • 2021-08-12 03:11:14
  • OfStack

In computer programs, algorithms are the soul and the essence of programs. The efficiency of program execution depends directly on the algorithm, so computer algorithm is a compulsory course in computer courses. The algorithm can quickly calculate the results we need, such as judging prime numbers, which is a very basic content. How to operate it concretely? The following site shows you how to judge whether a number is a prime number in python.

Prime number: A natural number greater than 1 that cannot be divisible (2, 3, 5, 7, etc.) by other natural numbers (prime numbers) except 1 and itself, in other words, the number has no other factors except 1 and itself.

Judgment code:


def isprime(a):
 if isinstance(a,int)==False:
  return False
 if a<=1:
  return False
 if a==2:
  return True
 flag=1
 x=int(pow(a,0.5))+1
 for n in range(2,x):
  if a%n == 0:
   flag=0
   break
 if flag==1:
  return True
 else:
  return False

The above is the code to judge whether a number is a prime number

Python prime number judgment instance extension:

A natural number greater than 1 cannot be divisible (2, 3, 5, 7, etc.) by other natural numbers (prime numbers) except 1 and itself, in other words, the number has no other factors except 1 and itself.


# -*- coding: UTF-8 -*-
 
# Filename : test.py
# author by : www.runoob.com
 
# Python  The program is used to detect whether the number entered by the user is prime or not 
 
#  User input number 
num = int(input(" Please enter 1 Number : "))
 
#  Prime number greater than  1
if num > 1:
  #  View factor 
  for i in range(2,num):
    if (num % i) == 0:
      print(num," Not prime number ")
      print(i," Multiply by ",num//i," Yes ",num)
      break
  else:
    print(num," Is a prime number ")
    
#  If the number you enter is less than or equal to  1 Is not a prime number 
else:
  print(num," Not prime number ")

The output of executing the above code is:

$ python3 test.py
Please enter 1 number: 1
1 is not a prime number
$ python3 test.py
Please enter 1 number: 4
4 is not a prime number
2 times 2 is 4
$ python3 test.py
Please enter 1 number: 5
5 is a prime number


Related articles: