UVa10006 Carmichael Numbers【素數判定+快速模冪】
阿新 • • 發佈:2019-01-26
問題簡述:參見上述連結。
問題分析:
這是一個卡爾邁勒數判定問題,只要讀懂題意就簡單了。
卡爾邁勒數是數論中的一個重要概念。
程式說明:
函式isprime()不是一個真正意義上的素數判斷函式,只進行奇數判定,對於本題條件是沒有問題的。
函式powermod()是模冪計算函式。
AC的C++語言程式如下:
/* UVa10006 Carmichael Numbers */ #include <iostream> #include <cmath> using namespace std; // 試除法判斷一個數是否為素數 bool isprime(int n) { int end2, i; end2 = sqrt(n); for(i=3; i<=end2; i+=2) { if(n % i == 0) break; } return i > end2; } // 模冪計算 int powermod(long long a, int n, int m) { long long res = 1; while(n) { if(n & 1) { // n % 2 == 1 res *= a; res %= m; } a *= a; a %= m; n >>= 1; } return res; } int main() { int n; while(cin >> n && n) { if(isprime(n)) cout << n << " is normal." << endl; else { int i; for(i=2; i<n; i++) if(powermod(i, n, n) != i) break; if(i < n) cout << n << " is normal." << endl; else cout << "The number " << n << " is a Carmichael number." << endl; } } return 0; }