费马素性检验

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

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