找到米勒拉宾的巅峰时期

时间:2018-05-26 21:39:02

标签: lua primality-test

我认为使用Lua正确实现了miller-rabin算法,我正在努力获得素数的一致回报。看起来我的实现只有一半的时间。虽然如果我尝试在python中实现类似的代码,那么该代码可以100%的时间工作。有人能指出我正确的方向吗?

--decompose n-1 as (2^s)*d
local function decompose(negOne)
  exponent, remainder = 0, negOne
  while (remainder%2) == 0 do 
    exponent = exponent+1
    remainder = remainder/2
  end
  assert((2^exponent)*remainder == negOne and ((remainder%2) == 1), "Error setting up s and d value")
  return exponent, remainder
end

local function isNotWitness(n, possibleWitness, exponent, remainder)
  witness = (possibleWitness^remainder)%n

  if (witness == 1) or (witness == n-1) then
    return false
  end

  for _=0, exponent do
    witness = (witness^2)%n
    if witness == (n-1) then
      return false
    end
  end

  return true
end

--using miller-rabin primality testing
--n the integer to be tested, k the accuracy of the test
local function isProbablyPrime(n, accuracy)
  if n <= 3 then
    return n == 2 or n == 3
  end
  if (n%2) == 0 then
    return false
  end

  exponent, remainder = decompose(n-1)

  --checks if it is composite
  for i=0, accuracy do
    math.randomseed(os.time())
    witness = math.random(2, n - 2)
    if isNotWitness(n, witness, exponent, remainder) then
      return false
    end
  end

  --probably prime
  return true
end

if isProbablyPrime(31, 30) then
  print("prime")
else
  print("nope")
end

1 个答案:

答案 0 :(得分:3)

Python有任意长度整数。 Lua没有 问题出在witness = (possibleWitness^remainder)%n Lua无法直接计算29^15 % 31的确切结果 数字n < sqrt(2^53)有一个解决方法:

witness = mulmod(possibleWitness, remainder, n)

其中

local function mulmod(a, e, m)
   local result = 1
   while e > 0 do
      if e % 2 == 1 then 
         result = result * a % m
         e = e - 1
      end
      e = e / 2
      a = a * a % m
   end
   return result
end