返回顶部

收藏

费马素性检验

更多

费马素性检验(Fermat Primality Test),判断是否为素数。

[Ruby]代码

def fermat(num, iter)
  #num is the number to test, iter is the maximum number of iterations (higher is more accurate)
  rand = 1+rand(num-1)
  for i in 1..iter
    if (rand**(num-1))%num == 0
      return false
    else
      rand = 1+rand(num-1)
    end
  end
  return true
end

#Example
puts fermat(16, 100) #=>false
puts fermat(7, 100)  #=>true
puts fermat(221, 100) #=>Counterexample. Called a Fermat Liar. Returns true (if the iter is low enough (usually)) actually is composite

标签:ruby/rails

收藏

0人收藏

支持

0

反对

0

发表评论