LightOJ - 1220 (唯一分解定理)

题意:给定n,n = b^p,b与p均未给出,求最大的p。

用唯一分解定理分解n,p就是n所有因子得幂得最大公约数。如 12 = 2^2*3,p = gcd(2,1) = 1,n为负数时p必须处理为奇数,因为偶数时n就是正数了。

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
const int sz = 1000100;

int prime[sz/10],vis[sz],b[1005],cnt,tot;

void primee(){
	memset(vis,0,sizeof(vis));
	for(long long i = 2;i<sz;++i){
		if(vis[i] == 0){
			prime[tot++] = i;
			for(long long j = i*i;j<sz;j += i)
			vis[j] = 1;
		}
	}
}

void getprime(int n){
	memset(b,0,sizeof(b));
	for(int i = 0;prime[i]*prime[i] <= n&&i < tot;++i){
		if(n % prime[i] == 0){
			while( n % prime[i] == 0){
				++b[cnt];
				n /= prime[i];
			}
			++cnt;}
	}
	if(n != 1){
		b[cnt++] = 1;
	}
}

int gcd(int a,int b)
{
    return b?gcd(b,a%b):a;
}
int main(){
	tot = 0;
	primee();
	int t;
	long long n;
	scanf("%d",&t);
	int ok,q,id = 0;
	while(t--){
		ok = 1;
		scanf("%lld",&n);
		if(n < 0) n = -n,ok = 0;
		cnt = 0;
		getprime(n);
		q = b[0];
		if(ok == 0){
			while(q % 2 == 0) q /= 2;
			for(int i = 0;i<cnt;++i){
				while(b[i] % 2 == 0) b[i] /= 2;
				q = gcd(q,b[i]);
			}
		}
		else for(int i = 0;i<cnt;++i) q = gcd(q,b[i]);
		printf("Case %d: %d\n",++id,q);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/dukig/article/details/89438073