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

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

最新文章

  1. JS for循环
  2. 浅谈php生成静态页面
  3. 【转】C#类似Jquery的html解析类HtmlAgilityPack基础类介绍及运用
  4. Leetcode: Longest Repeating Character Replacement && G 面经
  5. 【原创】基于Memcached 实现用户登录的Demo(附源码)
  6. 电子技术中的dB
  7. Android种 adb是什么(转)
  8. CF Pangram
  9. C# - Generic
  10. HW5.20
  11. c# 用正则表达式获取开始和结束字符串中间的值
  12. h5新特性
  13. C语言顺序栈实现
  14. Wayland中的跨进程过程调用浅析
  15. (译)Windsor入门教程---第五部分 添加日志功能
  16. BZOJ1854_游戏_KEY
  17. 用swing做一个简单的正则验证工具
  18. [C++] const与指针的关系
  19. [原]openstack-kilo--issue(十三)Unauthorized: The request you have made requires authentication. (HTTP 401) (Request
  20. 数据结构与算法--最短路径之Bellman算法、SPFA算法

热门文章

  1. Hex Editor实现Notepad++16进制编辑功能
  2. cocosbuilder3.0使用小记
  3. FDR
  4. 安装完openfire之后打不开的解决方案
  5. sphinx搜索引擎架构图
  6. 通过joystick遥感和按键控制机器人--11
  7. Apache的https协议配置
  8. kuangbin_ShortPath A (POJ 2387)
  9. Git-rebase与merge小结
  10. 【Unity3D技巧】一个简单的Unity-UI框架的实现