gpt4 book ai didi

c++ - ruby 程序 : Trailing zeros in the nth Power of a numbers factorial

转载 作者:行者123 更新时间:2023-11-30 03:36:30 27 4
gpt4 key购买 nike

我正在尝试将 C++ 代码移植到 Ruby。运行脚本会出现“执行超时”错误。

这是 Ruby 代码:

t = gets.to_i
t.times do
a = gets.to_i
b = gets.to_i
c = 0
j = 5
until j <= a do
j*5
c += a/j
end
puts c*b
end

这是C++代码:

#include<iostream>

main()
{
long t, a, b, i = 0, j, c;
std::cin >> t;
for( ; i < t ; i++)
{
std::cin >> a >> b;
c = 0;
for( j = 5 ; j <= a ; j *= 5)
c += a/j;
std::cout << c * b << '\n';
}
}

我的输入是:

2
100
10
5
4

我的任何输出是:

240
4

有两个测试用例:

  1. 尾随 (100!)^10 的零数
  2. 尾随 (5!)^4 的零数

最佳答案

我会像这样在 Ruby 中编写计算:

a = 100
b = 10
((1..a).inject(:*)**b).to_s[/0*$/].size
#=> 240

其中(1..a).inject(:*)计算a!**b为指数函数,to_s 将数字转换为字符串,[/0*$/] 提取所有尾随零并 size 计算它们...

关于c++ - ruby 程序 : Trailing zeros in the nth Power of a numbers factorial,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40662948/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com