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