Uva 10006 Carmichael Numbers 快速幂

本文介绍了一种用于检测Carmichael数的算法,并通过快速幂运算提高效率。该算法首先判断输入数字是否为素数,若不是则进一步检查是否满足Carmichael数的条件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

An important topic nowadays in computer science is cryptography. Some people even think that cryptography is the only important field in computer science, and that life would not matter at all without cryptography. Alvaro is one of such persons, and is designing a set of cryptographic procedures for cooking paella. Some of the cryptographic algorithms he is implementing make use of big prime numbers. However, checking if a big number is prime is not so easy. An exhaustive approach can require the division of the number by all the prime numbers smaller or equal than its square root. For big numbers, the amount of time and storage needed for such operations would certainly ruin the paella.

题意:给定这样的一个定义:给你一个数n,对于任意的x(1< x < n),都有x^n ≡x(mod n)。那么就称这个数Carmichael number。如果不是,则输出”is normal“。

题解:对于一个数n的判断次数就是2~n-1。如果不处理幂运算,那么肯定是会超时得。我们可以采用快速幂的算法。要注意在进行快速幂之前先判断一次n是否为素数,如果是素数那么就is normal 并且continue了。不进行这样的操作很有可能超时。

#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<queue>
#include<cmath>
using namespace std;
long long int mod_pow(long long int x,long long int n,long long int mod)
{
    long long int ret=1;
    while(n>0)
    {
        if(n&1)
            ret=ret*x%mod;
        x=x*x%mod;
        n>>=1;
    }
    return ret;
}
bool prime(int x)
{
    for(int i=2;i<=sqrt(x);i++)
    {
        if(x%i==0)
        return false;
    }
    return true;
}

int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        if(n==0)
            break;
        bool flag=true;
        if(prime(n))
        {
             printf("%d is normal.\n",n);
             continue;
        }
        for(int i=2;i<n;i++)
        {
            if(mod_pow(i,n,n)!=i)
            {
                flag=false;
                break;
            }
        }
        if(!prime(n)&&flag)
            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、付费专栏及课程。

余额充值