1. 程式人生 > >POJ 3641 Pseudoprime numbers (快速冪)

POJ 3641 Pseudoprime numbers (快速冪)

判斷 tables else main while als can 進制 指數

題意:給出a和p,判斷p是否為合數,且滿足a^p是否與a模p同余,即a^p%p與a是否相等

算法:篩法打1萬的素數表預判p。再將冪指數的二進制形式表示,從右到左移位,每次底數自乘。

#include <cstdio>
#include <cstring>
typedef long long LL;

int p[10010];
bool np[100010];
int cntp;

void SievePrime(int n) {
	memset(np, true, sizeof(np));
	np[0] = np[1] = false;
	for (int i = 2; i <= n; ++i) {
		if (np[i]) p[cntp++] = i;
		for (int j = i * 2; j <= n; j+=i) {
			np[j] = false;
		}
	}
}

LL Ksm(LL a, LL b, LL p) {
	LL ans = 1;
	while (b) {
		if (b & 1) {
			ans = (ans * a) % p;
		}
		a = (a * a) % p;
		b >>= 1;
	}
	return ans;
}

bool IsPrime(LL a) {
	if (a <= 100000) return np[a];
	for (int i = 0; i < cntp; ++i) {
		if (a % p[i] == 0) return false;
	}
	return true;
}

int main() {
	SievePrime(100000);
	LL a, p;
	while (scanf("%lld%lld", &p, &a) != EOF && p) {
		if (IsPrime(p)) {
			printf("no\n");
		}
		else {
			printf("%s\n", Ksm(a, p, p) == a ? "yes" : "no");
		}
	}

	return 0;
}

POJ 3641 Pseudoprime numbers (快速冪)