c++ - Calculate LCM of N numbers modulo 1000000007 -
i solving following problem on lcm : calculate lcm of n numbers modulo 1000000007
my approach :
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= %t; = 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; (i = 0; < 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; }
i getting wrong answer when submit solution. constraints are:
1<=n<=1000 , 1<=a[i]<=10000
i guess getting wrong answer because of overflow. how can improve code?
thanks!
1000000007
big me take example. let me use 17
example:
lcms(10, 9, 8) % 17 = lcm(10, lcm(9, 8)) % 17 = lcm(10, 72) % 17 = 360 % 17 = 3
this code doing:
lcms(10, 9, 8) % 17 = lcm(10, lcm(9, 8) % 17) % 17 = lcm(10, 72 % 17) % 17 = lcm(10, 4) % 17 = 40 % 17 = 6
which wrong.
Comments
Post a Comment