UVA - 10006 Carmichael Numbers

//挑战P122
#include <iostream>
#include <cstring>
using namespace std;
const int MAXN = 65010;
int notprime[MAXN];
int n;
typedef long long ll;
void init()
{
	memset(notprime, 0, sizeof(notprime));
	for (int i = 2; i <= MAXN; i++) //注意此处不是 i * i <= MAXN, 因为现在不是判断一个数是不是素数,而是要用这个范围的素数,通过筛法筛掉所有的合数 
	if (!notprime[i])
	{
		for (int j = 2 * i; j <= MAXN; j += i)
		notprime[j] = 1;
	}
}
ll mod_pow(ll x, ll n, ll mod)
{
	ll res = 1;
	while (n > 0)
	{
		if (n & 1) res = res * x % mod;
		x = x * x % mod;
		n >>= 1;
	}
	return res;
}
bool is_Carmichael(int n)
{
	for (int i = 2; i < n; i++)
	if (mod_pow(i, n, n) != i)
	return false;
	return true;
}

int main()
{
	init();
	
	while (cin >> n)
	{
		if (!n) break;
		if ( notprime[n] && is_Carmichael(n) ) 
		cout << "The number " << n << " is a Carmichael number." << endl;
		else
		cout << n << " is normal." << endl;
	}
	return 0;
} 



//挑战P122
//相比法一,改了mod_pow函数,将循环改为了递归
#include <iostream>
#include <cstring>
using namespace std;
const int MAXN = 65010;
int notprime[MAXN];
int n;
typedef long long ll;
void init()
{
	memset(notprime, 0, sizeof(notprime));
	for (int i = 2; i <= MAXN; i++) //注意此处不是 i * i <= MAXN, 因为现在不是判断一个数是不是素数,而是要用这个范围的素数,通过筛法筛掉所有的合数 
	if (!notprime[i])
	{
		for (int j = 2 * i; j <= MAXN; j += i)
		notprime[j] = 1;
	}
}
ll mod_pow(ll x, ll n, ll mod)
{
	if (!n) return 1;
	ll res = mod_pow( x * x % mod, n / 2, mod);
	if (n & 1)
	res = res * x % mod;
	return res;
}
bool is_Carmichael(int n)
{
	for (int i = 2; i < n; i++)
	if (mod_pow(i, n, n) != i)
	return false;
	return true;
}

int main()
{
	init();
	
	while (cin >> n)
	{
		if (!n) break;
		if ( notprime[n] && is_Carmichael(n) ) 
		cout << "The number " << n << " is a Carmichael number." << endl;
		else
		cout << n << " is normal." << endl;
	}
	return 0;
} 


posted @ 2017-08-26 09:22  mofushaohua  阅读(288)  评论(0编辑  收藏  举报