HUT-XXXX 数字游戏续 质因子分解

这题竟然用java也可以过,因该算是最简单的吧了。当然另外的两重for循环的写法也算是很简单的了。这里就直接写素因子分解的写法。

对于A中的数,我们可以将每个数都进行素因子分解,最后保留各个质数的指数,对B进行同样操作,然后在去两者指数的min值就可以了。这里要对大质数进行特殊处理。

代码如下:

#include <cstdlib>

#include <cstdio>

#include <cstring>

#include <algorithm>

#include <map>

#define MOD 1000000000

using namespace std;



typedef long long int Int64;



int N, M, a[100005], b[100005], flag;



Int64 ret;



map<int,int>mp;



void magic(int x, int tot[], int f)

{

    for (int i = 2;  i <= 100000; ++i) {

        if (x == 1) { return; }

        while (x % i == 0) {

            ++tot[i];

            x /= i;

        }

    }

    if (x != 1) {

        if (f) {

            if (mp.count(x)) {

                ret *= x;

                if (ret >= MOD) {

                    flag = 1;

                    ret %= MOD;

                }

                --mp[x];

            }

        }

        else {

            ++mp[x];

        }

    }

}



int _pow(Int64 a, Int64 b)

{

    Int64 ans = 1;

    while (b) {

        if (b & 1) {

            ans *= a;

            if (ans >= MOD) {

                flag = 1;

                ans %= MOD;

            }

        }

        a *= a;

        if (a >= MOD) {

            flag = 1;

            a %= MOD;

        }

        b >>= 1;

    }

    return ans;

}



int main()

{

    int c;

    while (scanf("%d", &N) == 1) {

        ret = 1;

        flag = 0;

        memset(a, 0, sizeof (a));

        memset(b, 0, sizeof (b));

        mp.clear();

        for (int i = 1; i <= N; ++i) {

            scanf("%d", &c);

            magic(c, a, 0);

        }

        scanf("%d", &M);

        for (int j = 1; j <= M; ++j) {

            scanf("%d", &c);

            magic(c, b, 1);

        }

        for (int i = 2; i <= 100000; ++i) {

            ret *= _pow(i, min(a[i], b[i]));

            if (ret >= MOD) {

                flag = 1;

                ret %= MOD;

            }

        }

        printf(flag ? "%09I64d\n" : "%I64d\n", ret);

    }

    return 0;

}

你可能感兴趣的:(游戏)