簡體   English   中英

在 python 中使用 Miller Rabin 測試計算素數問題

[英]counting prime number issue with Miller Rabin test in python

我正在嘗試通過 Miller Rabin 測試用上限和下限來計算素數,比如在 1000 到 1000000 之間會產生多少個素數建議將不勝感激並將米勒拉賓代碼粘貼在下面等待您的反饋

# Python3 program Miller-Rabin primality test 
import time 
import random 
lower=int(input("Enter the lower limit for the range:"))
upper=int(input("Enter the upper numbers for limit the range:"))
# Utility function to do 
# modular exponentiation. 
# It returns (x^y) % p 
def power(x, y, p): 

    # Initialize result 
    res = 1; 

    # Update x if it is more than or 
    # equal to p 
    x = x % p; 
    while (y > 0): 

        # If y is odd, multiply 
        # x with result 
        if (y & 1): 
            res = (res * x) % p; 

        # y must be even now 
        y = y>>1; # y = y/2 
        x = (x * x) % p; 

    return res; 

# This function is called 
# for all k trials. It returns 
# false if n is composite and 
# returns false if n is 
# probably prime. d is an odd 
# number such that d*2<sup>r</sup> = n-1 
# for some r >= 1 
start_time = time.time()
def miillerTest(d, n): 

    # Pick a random number in [2..n-2] 
    # Corner cases make sure that n > 4 
    a = 2 + random.randint(1, n - 4); 

    # Compute a^d % n 
    x = power(a, d, n); 

    if (x == 1 or x == n - 1): 
        return True; 

    # Keep squaring x while one 
    # of the following doesn't 
    # happen 
    # (i) d does not reach n-1 
    # (ii) (x^2) % n is not 1 
    # (iii) (x^2) % n is not n-1 
    while (d != n - 1): 
        x = (x * x) % n; 
        d *= 2; 

        if (x == 1): 
            return False; 
        if (x == n - 1): 
            return True; 

    # Return composite 
    return False; 

# It returns false if n is 
# composite and returns true if n 
# is probably prime. k is an 
# input parameter that determines 
# accuracy level. Higher value of 
# k indicates more accuracy. 
def isPrime( n, k): 
    # Corner cases 
    if (n <= 1 or n == 4): 
        return False; 
    if (n <= 3): 
        return True; 

    # Find r such that n = 
    # 2^d * r + 1 for some r >= 1 
    d = n - 1; 
    while (d % 2 == 0): 
        d //= 2; 

    # Iterate given nber of 'k' times 
    for i in range(k): 
        if (miillerTest(d, n) == False): 

            return False; 

    return True; 

# Driver Code 
# Number of iterations 
k = 4; 

print("All primes smaller than 200: "); 
for n in range(100 ,1000): 
    if (isPrime(n, k)):  
        print(n , end=" "); 
def count(n_lower,n_upper):
        count1=0
        for j in range(n_lower,n_upper):
            for i in range(1,j):
                if j%i==0:
                   factor=i
            if factor>1:
                count1+=1
        return count1

print(count(lower,upper))
end_time = time.time()
print("Following are the composite numbers smaller b/w 10^5 to 10^6")
print("Total time:%0.5f" % (end_time - start_time))

如果你想要一個創建算法 k 測試的測試,這樣就不需要隨機數和增加迭代,你可以使用這個:


def ltrailing(N):
    return len(str(bin(N))) - len(str(bin(N)).rstrip('0'))

def MillerRabin(N, primetest, iterx, powx, withstats=False): 
  primetest = pow(primetest, powx, N) 
  if withstats == True:
     print("first: ",primetest) 
  if primetest == 1 or primetest == N - 1: 
    return True 
  else: 
    for x in range(0, iterx-1): 
       primetest = pow(primetest, 2, N) 
       if withstats == True:
          print("else: ", primetest) 
       if primetest == N - 1: return True 
       if primetest == 1: return False 
  return False 

def sfactorint_isprime(N, withstats=False):
    if N == 2:
      return True
    if N % 2 == 0:
      return False
    if N < 2:
        return False
    iterx = ltrailing(N - 1)
    """ This k test is an algorithmic test builder instead of using
        random numbers. The offset of k, from -2 to +2 produces pow tests
        that fail or pass instead of having to use random numbers and more
        iterations. All you need are those 5 numbers from k to get a 
        primality answer. 
    """
    k = pow(N, (1<<N.bit_length())-1, 1<<N.bit_length()) - 1
    t = N >> iterx
    tests = [k-2, k-1, k, k+1, k+2]
    for primetest in tests:
        if primetest >= N:
            primetest %= N
        if primetest >= 2:
            if MillerRabin(N, primetest, iterx, t, withstats) == False:
                return False
    return True

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM