Problem Description
We say that x is a perfect square if, for some integer b, x = b2. Similarly, x is a perfect cube if, for some integer b, x = b3. More generally, x is a perfect pth power if, for some integer b, x = bp. Given an integer x you are to determine the largest p such that x is a perfect pth power.
Input
Each test case is given by a line of input containing x. The value of x will have magnitude at least 2 and be within the range of a (32-bit) int in C, C++, and Java. A line containing 0 follows the last test case.
Output
For each test case, output a line giving the largest integer p such that x is a perfect p<i>th</i> power.
Sample Input
17 1073741824 25 0
Sample Output
1 30 2
题意:给出一个整数x,把x写成x=a^p,求p最大是多少?
思路:把x分解质因数,x = a1^b1 * a2^b2 … ak^bk,则最终结果为b1,b2,…bk的最大公约数。注意x有可能是负数。
如果x是负数,则要把求得的答案一直除以2,直到结果是一个奇数,因为一个数的偶数次方不可能是负数。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define ll long long
ll p[1001],num[1001];
ll cnt;
void fenjie(ll n)
{
memset(p,0,sizeof(p));
memset(num,0,sizeof(num));
cnt=0;
for(ll i=2;i*i<=n;i++)
{
if(n%i==0)
{p[++cnt]=i;
num[cnt]=0;
while(n%i==0)
{
num[cnt]++;
n/=i;
}
}
}
if(n!=1)
{
p[++cnt]=n;
num[cnt]=1;
}
}
ll gcd(ll a,ll b)
{
return b==0?a:gcd(b,a%b);
}
int main()
{
ll x;
while(~scanf("%lld",&x))
{
if(x==0)
break;
ll ans=0;
int flag=0;
if(x<0)
{
x=-x;
flag=1;
}
fenjie(x);
for(ll i=1;i<=cnt;i++)
{
ans=gcd(ans,num[i]);}
if(flag)
{while(ans%2==0)
ans/=2;}
printf("%lld\n",ans);
}
return 0;
}