UVA 10006
An importanttopic nowadays in computer science is cryptography. Some people even think thatcryptography is the only important field in computer science, and that lifewould not matter at all without cryptography.
Alvaro is one ofsuch persons, and is designing a set of cryptographic procedures for cookingpaella. ´ Some of the cryptographic algorithms he is implementing make use ofbig prime numbers.
However, checking if a big number is prime is not soeasy. An exhaustive approach can require the division of the number by all theprime numbers smaller or equal than its square root. For big numbers, theamount of time and storage needed for such operations would certainly ruin thepaella. However, some probabilistic tests exist that offer high confidence atlow cost. One of them is the Fermat test.
Let a be a randomnumber between 2 and n−1 (being n the number whose primality we are testing).Then, n is probably prime if the following equation holds:
a^n mod n = a
If a number passesthe Fermat test several times then it is prime with a high probability.
Unfortunately, there are bad news. Some numbers that arenot 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 testif a given number is a Carmichael number. Hopefully, the teams that fulfill thetask will one day be able to taste a delicious portion of encrypted paella. Asa side note, we need to mention that, according to Alvaro, the main advantageof encrypted ´ paella over conventional paella is that nobody but you knowswhat you are eating.
Input
The input will consist of a series of lines, eachcontaining a small positive number n (2 < n < 65000). A number n = 0 willmark the end of the input, and must not be processed.
Output
For each number in the input, you have to print if it isa Carmichael number or not, as shown in the sample output.
Sample Input
1729
17
561
1109
431
0
Sample Output
The number 1729 is a Carmichael number. 17 is normal.
The number 561 is a Carmichael number.
1109normal.
431 normal.
一.题意分析
求一个合数n使得对于任何比n小的数a都有pow(a,n)%n == a
二.思路过程
在给出的数值范围内,循环进行以下操作
1. 先判断n是不是素数
2. 遍历比n小的数判断取余是否等于n。如果等于的话,就输出n。
三. 代码
<span style="font-family:Courier New;font-size:18px;">#include<stdio.h>
#include<math.h>
int num;
int pow_mod(int a ,int n ,int m) {
if(n == 1)
return a;
int x = pow_mod(a , n / 2 , m);
long long ans = (long long) x * x % m;
if(n % 2 == 1)
ans = ans * a % m;
return (int)ans;
}
int main () {
int num;
while(scanf("%d",&num) && num) {
bool flag = false;
for (int i = 2 ; i < sqrt(num) ; i++) {
if(num % i == 0) {
flag = true;
break;
}
}
if(!flag) {
printf("%d is normal.\n",num);
continue;
}
flag = false;
for (int i = 1 ; i < num ;i++) {
if(pow_mod(i , num , num) != i) {
flag = true;
break;
}
}
if(!flag)
printf("The number %d is a Carmichael number.\n",num);
else
printf("%d is normal.\n",num);
}
}</span>