我正在解决以下关于LCM的问题: 计算N个数的LCM模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; }
提交解决方案时,我得到了错误答案。约束是:
1<=N<=1000 and 1<=A[i]<=10000
在IDEONE
我猜我因为溢出而得到错误答案。如何改善我的守则?
谢谢!
1000000007太大了,我不能举个例子。让我17举个例子:
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
哪有错
同样在IDEONE