gpt4 book ai didi

c++ - 计算 N 个数的 LCM 模 1000000007

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:10:34 25 4
gpt4 key购买 nike

我在 LCM 上解决了以下问题:Calculate LCM of N numbers modulo 1000000007

我的方法:

typedef unsigned long long ull;
const ull mod=1000000007;
ull A[10009];
/*Euclidean GCD*/
ull gcd(ull a,ull b)
{
while( b != 0)
{
ull t = b;
b= a %t;
a = t;
}
return a;
}
ull lcm(ull a, ull b)
{
return (a/gcd(a,b))%mod*(b%mod);
}
ull lcms(int l ,ull * A)
{
int i;
ull result;
result = 1;
for (i = 0; i < l; i++)
result = lcm(result, A[i])%1000000007;
return result;
}
int main()
{
int T;
cin>>T;
while(T--)/*Number of test cases*/
{
int N;
cin>>N;/*How many Numbers in Array*/
for(int i=0;i<N;++i)
{
cin>>A[i];//Input Array
}
cout<<lcms(N,A)%1000000007<<endl;
}
return 0;
}

当我提交我的解决方案时,我得到了 Wrong Answer。约束是:

1<=N<=1000
and 1<=A[i]<=10000

AT IDEONE

我想我因为溢出而得到了错误的答案。我如何改进我的代码?

谢谢!

最佳答案

1000000007 太大了,我无法举个例子。让我用 17 举例:

LCMS(10, 9, 8) % 17 =
LCM(10, LCM(9, 8)) % 17 =
LCM(10, 72) % 17 =
360 % 17 =
3

这就是您的代码所做的:

LCMS(10, 9, 8) % 17 =
LCM(10, LCM(9, 8) % 17) % 17 =
LCM(10, 72 % 17) % 17 =
LCM(10, 4) % 17 =
40 % 17 =
6

这是错误的。

ALSO AT IDEONE

关于c++ - 计算 N 个数的 LCM 模 1000000007,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16633449/

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