Home  >  Article  >  Backend Development  >  How to determine prime numbers in python

How to determine prime numbers in python

coldplay.xixi
coldplay.xixiOriginal
2021-03-09 17:35:0842388browse

How to judge prime numbers in python: first use python’s mathematical functions; then scan the prime numbers in a single line program, the code is [[ p for p in range(2, N) if 0 not in [ p% d for d in range(2,int(sqrt(p)].

How to determine prime numbers in python

The operating environment of this tutorial: windows7 system, python3.9 version, DELL G3 computer.

Python prime number judgment method:

1. Use python’s mathematical functions

import math 
 
def isPrime(n): 
  if n <= 1: 
  return False
  for i in range(2, int(math.sqrt(n)) + 1): 
  if n % i == 0: 
    return False
  return True

2. Single-line program to scan prime numbers

from math import sqrt 
N = 100
[ p for p in  range(2, N) if 0 not in [ p% d for d in range(2, int(sqrt(p))+1)] ]

Using python’s itertools module

from itertools import count 
def isPrime(n): www.jb51.net
  if n <= 1: 
    return False
  for i in count(2): 
    if i * i > n: 
      return True
    if n % i == 0: 
      return False

3. Two methods without using modules

Method 1:

def isPrime(n): 
  if n <= 1: 
    return False
  i = 2
  while i*i <= n: 
    if n % i == 0: 
      return False
    i += 1
  return True

Method 2:

def isPrime(n): 
  if n <= 1: 
    return False
  if n == 2: 
    return True
  if n % 2 == 0: 
    return False
  i = 3
  while i * i <= n: 
    if n % i == 0: 
      return False
    i += 2
  return True

eg: Find the prime number (prime number) between 20001 and 40001

Since it can only be digitized by 1 or by yourself, then It shows that only when the remainder is 0 twice, the code is as follows:

#!/usr/bin/python
 
L1=[]
for x in xrange(20001,40001):
 n = 0
 for y in xrange(1,x+1):
 if x % y == 0:
  n = n + 1
 if n == 2 :
 print x
 L1.append(x)
print L1

The result is as follows:

20011
20021
20023
20029
20047
20051
20063
20071
20089
20101
20107
20113
20117
20123
20129
20143
20147
20149
20161
20173
….

Related free learning recommendations: python video tutorial

The above is the detailed content of How to determine prime numbers in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn