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.
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步