LCM of n numbers modulo 1000000007

為{幸葍}努か 提交于 2019-11-28 10:08:02

问题


I have to find LCM of n numbers MODULO 10^9+7.My approach is find LCM of two numbers and then MOD them.Then take the LCM of next element and the answer obtained from the previous iteration and MOD them.Do this for all elements.Is it wrong ?


回答1:


Yes, it is wrong. I have been working on a similar problem.

You must be familiar with the following property of MOD:

PROPERTY 1: (a*b*c*d...*p*q) % MOD = (a%MOD)(b%MOD)(c%MOD).....(q%MOD);

but this is not the case with LCM.

LCM(a,b)=a*b/GCD(a,b).

LCM(LCM(a,b),c)=LCM(a,b)*c/GCD(LCM(a,b),c).

Whenever LCM becomes greater than the MOD, the above mentioned property gets destroyed. You must try to find LCM in terms of products of different numbers in numerator only.

This can be done by factorizing all the numbers and keeping the record of highest powers of various factors.

LCM = (2^a)(3^b).... Now you can easily multiply them iteratively and also keep the limit under MOD by using property 1.




回答2:


Just for future reference, here's a C++ implementation that uses no prime factorization.

One possible solution is to keep an array of factors for the answer. Each factor will be each number from 1..N, divided by GCD(number, [all previous numbers]). For this to work, you have to code a special GCD that computes the result between a single number and an array of factors. This C++ code shows how this would work:

#include <iostream>
#include <vector>
#define lli long long int
using namespace std;

vector<lli> T;

lli gcd(lli a, lli b) {
    if(b == 0) 
        return a;
    return gcd(b, a%b);
}

lli gcd_vector(vector<lli>& a, lli b) {
    lli ma = 1;
    for(int i=0; i<T.size(); i++)
        ma = ma*T[i]%b;
    return gcd(b, ma);
}

int main() {
    lli answer = 1;
    for(int i=1; i<=1000; i++) {
        lli factor = i/gcd_vector(T, i); 
        T.push_back(factor);
        answer = (answer*factor)%1000000007;
    }

    cout << answer << endl;
}


来源:https://stackoverflow.com/questions/24574299/lcm-of-n-numbers-modulo-1000000007

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!