标签:
Time Limit: 3000MS | Memory Limit: Unknown | 64bit IO Format: %lld & %llu |
Description
Carmichael Numbers |
However, some probabilistic tests exist that offer high confidence at low cost. One of them is the Fermat test.
Let a be a random number between 2 and n - 1 (being n the number whose primality we are testing). Then,
n is probably prime if the following equation holds:
Unfortunately, there are bad news. Some numbers that are not prime still pass the Fermat test with every number smaller than themselves. These numbers are called Carmichael numbers.
In this problem you are asked to write a program to test if a given number is a Carmichael number. Hopefully, the teams that fulfill the task will one day be able to taste a delicious portion of encrypted paella. As a side note, we need to mention that, according to Alvaro, the main advantage of encrypted paella over conventional paella is that nobody but you knows what you are eating.
1729 17 561 1109 431 0
The number 1729 is a Carmichael number. 17 is normal. The number 561 is a Carmichael number. 1109 is normal. 431 is normal.
题意:我们把任意的1<x<n都有x^n % n == x % n的合数n称为Carmichael number,对于给定的数n,判断是否是Carmichael number。
解析:用筛法打个素数表,然后用快速幂判断。
PS:开始按照挑战编程上的非递归形式写的快速幂,不知道为什么WA,换成递归形式的就AC了。。。
AC代码:
#include <cstdio> #include <iostream> #include <algorithm> #include <cmath> #include <cstring> using namespace std; typedef long long LL; const int maxn = 65005; int prim[maxn+1]; void sieve(int n){ //区间筛法 int m = (int)sqrt(n + 0.5); memset(prim, 0, sizeof(prim)); prim[0] = prim[1] = -1; for(int i=2; i<=m; i++) if(!prim[i]){ for(int j=i*i; j<=n; j+=i) prim[j] = -1; } } LL mod_pow(int a, int p, int n){ //快速幂 if(!p) return 1; LL ans = mod_pow(a, p/2, n); ans = ans * ans % n; if(p & 1) ans = ans * a % n; return ans; } bool solve(int n){ for(int i=2; i<n; i++) if(mod_pow(i, n, n) != i) return false; return true; } int main(){ #ifdef sxk freopen("in.txt", "r", stdin); #endif // sxk sieve(maxn); int n; while(scanf("%d", &n)!=EOF && n){ if(prim[n] && solve(n)) printf("The number %d is a Carmichael number.\n", n); else printf("%d is normal.\n", n); } return 0; }
UVa 10006 Carmichael Numbers (快速幂 + 素性测试)
标签:
原文地址:http://blog.csdn.net/u013446688/article/details/43309603