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;
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值