POJ-1365 Prime Land 简单素数分解

代码如下:

#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cstdio>
using namespace std;

int p[40010], a[10000], b[10000];

void pre()
{
    for (int i = 4; i <= 40010; i += 2) {
        p[i] = 1;
    }
    for (int i = 3; i <= 200; i += 2) {
        if (!p[i]) {
            int k = 2 * i;
            for (int j = i*i; j <= 40010; j += k) {
                p[j] = 1;
            }
        }
    }
}

int _pow(int a, int b)
{
    int ans = 1;
    for (int i = 1; i <= b; ++i) {
        ans *= a;
    }    
    return ans;
}

int main()
{
    int cnt = 0, num = 1;
    pre();
    while (scanf("%d", &a[cnt]), a[cnt]) {
        scanf("%d", &b[cnt]);
        char t = getchar();
        if (t == '\n') {
            for (int i = 0; i <= cnt; ++i) {
                num *= _pow(a[i], b[i]);
            }
            num -= 1;
            int first = 1;
            for (int i = num; i >= 2; --i) {
                if (!p[i]) {
                    int c = 0;
                    while (num % i == 0) {
                        c++;
                        num /= i;
                    }
                    if (c) {
                        if (first) {
                            printf("%d %d", i, c);
                            first = 0;
                        }
                        else {
                            printf(" %d %d",i, c);
                        }
                    }
                }
            }
            puts("");
            cnt = 0;
        }
        else if (t == ' '){
            ++cnt;
        }
    }
    return 0;
}
posted @ 2012-07-14 00:33  沐阳  阅读(233)  评论(0编辑  收藏  举报