How to determine prime numbers in python

coldplay.xixi
Release: 2023-01-03 09:28:51
Original
42549 people have browsed it

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
Copy after login

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)] ]
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

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
….
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template