isprime.py

Created by nicolas-patrois

Created on May 30, 2018

413 Bytes

Primality test using random.


from random import randint

def pow(a,n,m):
 p=1
 for _ in range(n):
  p*=a
  p%=m
 return p

def isprime(n):
 d=n-1
 s=0
 while d%2==0:
  s+=1
  d/=2
 for _ in range(5):
  a=randint(2,n-2)
  x=pow(a,d,n)
  if x==1 or x==n-1:
   continue
  c=False
  for _ in range(s-1):
   x=pow(x,2,n)
   if x==1:
    return False
   if x==n-1:
    c=True
    break
  if c:
   continue
  return False
 return True

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.