I was 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= 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;
}
I am getting Wrong Answer when I submit my solution. The constraints are:
1<=N<=1000
and 1<=A[i]<=10000
I guess I am getting Wrong Answer because of Overflow. How can I improve my Code?
Thanks!
your approach is wrong as mentioned by johnchen902.
Here is my approach:
SEE AT IDEONE
1000000007
is too big for me to take as an example. Let me use17
for example:This is what your code doing:
Which is wrong.
ALSO AT IDEONE
Just factorize your numbers into arrays of prime numbers, calculate lcms over these arrays and then multiply them back into answer.
first primes are 2, 3, 5, 7, 11, 13, .. so, for example, 45 = 3^2 * 5 turns into {0, 2, 1, 0, 0, ...}
and