Perfect Pth Powers zoj 2124 pku1730 hunnu10585


测试数据中有负数。

湖南师范大学(hunnu OJ)提交时要使用%I64d

只要将n进行素因子分解,把所有素因子数目的gcd求出来就行。注意:n可能是负数,所以对于负数还需要将求出来的结果试除2,直到结果不是偶数才是最后负数的结果

#include<stdio.h>

#include<string.h>

#include<math.h>

#define nmax 65536

int prime[nmax], plen, cfactor[nmax], clen;

void init() {

	memset(prime, -1, sizeof(prime));

	int i, j;

	for (i = 2, plen = 0; i < nmax; i++) {

		if (prime[i]) {

			for (j = i + i; j < nmax; j += i) {

				prime[j] = 0;

			}

		}

	}

	for (i = 2, plen = 0; i < nmax; i++) {

		if (prime[i]) {

			prime[plen++] = i;

		}

	}

}

int gcd(int n, int m) {

	int te;

	if (n < m) {

		te = n, n = m, m = te;

	}

	if (m == 0) {

		return n;

	}

	return gcd(m, n % m);

}

int solve(long long n) {

	int i, te, res, cnt;

	long long m;

	m = n > 0 ? n : -n;

	te = (int) (sqrt(m * 1.0));

	for (i = 0, clen = 0; (i < plen) && (prime[i] <= te); i++) {

		if (m % prime[i] == 0) {

			cnt = 0;

			while (m % prime[i] == 0) {

				m /= prime[i];

				cnt++;

			}

			cfactor[clen] = cnt;

			clen++;

		}

	}

	if (clen == 0) {

		return 1;

	}

	for (i = 1, res = cfactor[0]; i < clen; i++) {

		res = gcd(res, cfactor[i]);

	}

	return res;

}



int main() {

#ifndef ONLINE_JUDGE

	freopen("t.txt", "r", stdin);

#endif

	init();

	long long n;

	int res;

	while (scanf("%I64d", &n) != EOF && n) {

		res = solve(n);

		if (n < 0) {

			while (!(res & 1)) {

				res >>= 1;

			}

		}

		printf("%d\n", res);

	}

	return 0;

}

你可能感兴趣的:(pku)