Compute the remainder with the following equation:
(x*y)%n = (x%n)*(y%n)%n
Code:
- /***************************************************************************
- * Copyright (C) 2008 by Liu Kaipeng *
- * LiuKaipeng at gmail dot com *
- ***************************************************************************/
- /* @JUDGE_ID 00000 10006 C++ "Carmichael Numbers" */
- #include <algorithm>
- #include <cstdio>
- #include <cstring>
- #include <deque>
- #include <fstream>
- #include <iostream>
- #include <list>
- #include <map>
- #include <queue>
- #include <set>
- #include <stack>
- #include <string>
- #include <vector>
- using namespace std;
- int const max_num = 65001;
- bool is_prime[max_num];
- void gen_primes()
- {
- for (int i = 0; i < max_num; ++i)
- is_prime[i] = true;
- for (int i = 2; i < max_num; ++i) {
- for (; i < max_num && !is_prime[i]; ++i) {}
- for (int j = 2; i*j < max_num; ++j)
- is_prime[i*j] = false;
- }
- }
- /*
- * Calculate a^n % n with a divide and conquer method
- */
- int power_mod(int a, int p, int n)
- {
- if (p == 1) return a;
- unsigned int r = power_mod(a, p/2, n);
- if (p % 2 == 0) {
- return r * r % n;
- } else {
- r = r * r % n;
- return r * a % n;
- }
- }
- bool is_carmichael(int n)
- {
- if (is_prime[n]) return false;
- for (int a = 2; a < n; ++a) {
- if (power_mod(a, n, n) != a) return false;
- }
- return true;
- }
- int main(int argc, char *argv[])
- {
- #ifndef ONLINE_JUDGE
- freopen((string(argv[0]) + ".in").c_str(), "r", stdin);
- freopen((string(argv[0]) + ".out").c_str(), "w", stdout);
- #endif
- gen_primes();
- for (int n; cin >> n && n != 0; )
- if (is_carmichael(n))
- cout << "The number " << n << " is a Carmichael number./n";
- else
- cout << n << " is normal./n";
- return 0;
- }