I was solving following problem on LCM : Calculate LCM of N numbers modulo 1000000007
My approach :
typedef unsigned long long ull;
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
vector<uul> lcm(vector<uul> a, vector<uul> b) {
vector<uul> res(a.size());
for (size_t i = 0; i < a.size(); ++i) {
res[i] = max(a[i], b[i]);
}
return res;
}
The correct approach would be to prime factorize the elements of the array and keep track of the highest power of every prime for each element. LCM will be the product of these primes raised to their highest power in the array.
1000000007
is too big for me to take as an example. Let me use 17
for example:
LCMS(10, 9, 8) % 17 =
LCM(10, LCM(9, 8)) % 17 =
LCM(10, 72) % 17 =
360 % 17 =
3
This is what your 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 is wrong.
ALSO AT IDEONE
your approach is wrong as mentioned by johnchen902.
Here is my approach:
for i=1 to n
a.take i_th number as x
b.reduce(devide) remaining numbers(i+1_th to n_th) by their gcd with x
c.multiply x to ans and take mod of ans
return ans
SEE AT IDEONE