Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

By property of mod operations , we can simply use Divide and Conquer + Recursion to solve it. Reference: https://www.khanacademy.org/math/applied-math/cryptography/modarithmetic/a/modular-exponentiation

My Ruby version is:

复制代码
DIV = 20

def ferma(x, y, n)
    c = 1
    for i in 0..y-1
        c = (c * x) % n         
    end
    #p "[#{x}^#{y} mod #{n} = #{c}]"
    return c
end

def div_conq_ferma(x, y, n)    
    #p "#{x}^#{y} mod #{n} = (#{x}^#{DIV})^#{y/DIV} * #{x}^#{y%DIV}, mod #{n}"

    mod1 = ferma(x, y % DIV, n)

    if (y > DIV)
        sub_mod0 = ferma(x, DIV, n)
        pwr_sub_mod0 = y / DIV
        mod0 = div_conq_ferma(sub_mod0, pwr_sub_mod0, n)
    else
        mod0 = 1
    end
    
    return ferma(mod1 * mod0, 1, n)
end
#
runcnt = gets.to_i
for i in 0..runcnt-1
    str = gets.split
    x = str[0].to_i
    y = str[1].to_i
    n = str[2].to_i    
    p div_conq_ferma(x, y, n)
end
View Code
复制代码

But seems Ruby is not fast enough to pass the second case. All Ruby submissions failed the 2nd case with TLE.

 

posted on   Tonix  阅读(193)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示