UVA 10006 Carmichael Numbers

题目链接:

https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=12&page=show_problem&problem=947

解题思路:

输入n,若满足如下两个条件,则n是Carmichael number 

(1)n不是素数 

(2)对于所有a(2<=a<n),有(a^n)%n = a 
 
先判断是否为素数,用素数筛选法,然后用快速幂取模,注意运算过程中的乘法溢出int ,要使用long long...

AC代码:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

typedef long long ll;
int not_prime[65005];

ll mod_pow(ll x,ll n,ll mod){
    ll res = 1;
    while(n){
        if(n&1)
            res = (res*x)%mod;
        x = (x*x)%mod;
        n >>= 1;
    }
    return res;
}

int main(){
    memset(not_prime,0,sizeof(not_prime));
    for(int i = 2; i <= 65000; i++){
        int tmp = 65000/i;
        for(int j = 2; j <= tmp; j++)
            not_prime[i*j] = 1;
    }
    int n;
    while(scanf("%d",&n),n){
        if(!not_prime[n]){
            printf("%d is normal.\n",n);
            continue;
        }
        int flag = 1;
        for(int i = 2; i < n; i++){
            if(mod_pow(i,n,n) != i){
                flag = 0;
                printf("%d is normal.\n",n);
                break;
            }
        }
        if(flag)
            printf("The number %d is a Carmichael number.\n",n);
    }
    return 0;
}


你可能感兴趣的:(快速幂,素数筛选法)