UVAlive 4119 (数学)

白书123页的例题,如果不看书上的证明自己写真是写不出来,好厉害~

#include <bits/stdc++.h>
using namespace std;
#define maxn 111

char P[111111];
int xishu[maxn]; //每一个指数下的系数
long long mod;

void deal () {
    int l = strlen (P);
    memset (xishu, 0, sizeof xishu);
    for (int i = 1; P[i] != ')'; ) {
        int cur = 0; // 系数
        int flag = 1; //是否是负数
        while (P[i] != 'n' && P[i] != ')') {
            char ch = P[i];
            if (ch == '+') {}
            else if (ch == '-') {
                flag = 0;
            }
            else {
                cur = cur*10 + (ch-'0');
            }
            i++;
        }
        if (cur == 0)
            cur = 1;
        if (!flag)
            cur *= (-1);
        i++;

        int zhishu = 0; //指数
        if (P[i] == '/') {
            zhishu = 0;
            xishu[zhishu] = cur;
            break;
        }
        else if (P[i] != '^') {
            zhishu = 1;
        }
        else if (P[i] == '^') {
            i++;
            while (isdigit (P[i])) {
                zhishu = zhishu*10 + (P[i]-'0');
                i++;
            }
        }
        xishu[zhishu] = cur;
    }
    mod = 0;
    for (int i = 0; i < l; i++) {
        if (P[i] == '/') {
            i++;
            for (; i < l; i++) {
                mod = mod*10 + (P[i]-'0');
            }
            return ;
        }
    }
    return ;
}

long long qpow (long long a, int b) {
    if (b == 0)
        return 1;
    long long ans = qpow (a, b>>1);
    ans = ans*ans%mod;
    if (b&1)
        ans = ans*a%mod;
    return ans;
}

long long cal (long long num) {
    if (num == 0)
        return xishu[0];
    long long ans = 0;
    for (int i = 0; i <= 100; i++) {
        if (xishu[i]) {
            ans += xishu[i]*qpow (num, i)%mod;
        }
    }
    return ans;
}

int main () {
    //freopen ("in", "r", stdin);
    int kase = 0;
    while (scanf ("%s", &P) == 1) {
        if (P[0] == '.')
            break;
        deal (); //分解出来每一项的系数
        bool ok = 1;
        for (long long k = 0; k <= 101; k++) {
            long long num = cal (k); //n用k代替
            if (num%mod != 0) {
                ok = 0;
                break;
            }
        }
        printf ("Case %d: ", ++kase);
        if (ok) {
            printf ("Always an integer\n");
        }
        else
            printf ("Not always an integer\n");
    }
    return 0;
}


你可能感兴趣的:(UVAlive 4119 (数学))