UVA - 10006 Carmichael Numbers

本文介绍了一种用于检测Carmichael数的算法,并通过快速幂取模的方法实现了该算法。文章提供了完整的C++代码实现,包括素数标记、快速幂取模函数等关键部分。

题目链接  http://acm.hust.edu.cn/vjudge/problem/19411


   输入n,若满足如下两个条件,则n是Carmichael number 
       1、n不是素数 
       2、对于所有a(2<=a<n),有(a^n)%n = a 

   快速幂取模,注意运算过程中的乘法溢出int 


#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <cmath>
#include <stack>
#include <map>
#include <set>
#define pi acos(-1)
#define LL long long
#define INF 0x3f3f3f3f
using namespace std;
typedef pair<int, int> P;
const int maxn = 1e5 + 5;
const int N = 65005;
int flag[maxn];
void chart()
{
    memset(flag, 0, sizeof(flag));
    for (int i = 2; i <= N; i++){
        if (flag[i]) continue;
        for (int j = 2; j * i <= N; j++)
            flag[j*i] = 1;
    }
}
int q_pow(int x, int n, int mod)
{
    int res = 1;
    while (n){
        if (n & 1) res = (LL)res * x % mod; // 会爆int。。。。
        x = (LL)x * x % mod;
        n >>= 1;
    }
    return res;
}
int main(void)
{
//	freopen("C:\\Users\\wave\\Desktop\\NULL.exe\\NULL\\in.txt","r", stdin);
    int i, j, n, ok;
    chart();
    while (~scanf("%d", &n) && n)
    {
        if (!flag[n]){   // 很无语 将这个判断放在后面的话会T 
            printf("%d is normal.\n", n);
            continue;
        }
        ok = 1;
        for (i = 2; i <= n-1; i++){
            if (q_pow(i, n, n) != i){
                ok = 0;
                break;
            }
        }
        if (ok)
            printf("The number %d is a Carmichael number.\n", n);
        else
            printf("%d is normal.\n", n);
    }

    return 0;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值