We say that x is a perfect square if, for some integer b, x = b 2. Similarly, x is a perfect cube if, for some integer b, x = b 3. More generally, x is a perfect pth power if, for some integer b, x = b p.
Given an integer x you are to determine the largest p such that x is a perfect p th power.
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.
For each test case, output a line giving the largest integer p such that x is a perfect p th power.
17 1073741824 25 0
1 30 2
题意:给出x,类似于完全平方数,让求使x=b^p的最大的p;
首先把x分解质因数,x = a1^b1 * a2^b2 … ak^bk,则最终结果p为b1,b2,…bk的最大公约数。
如果x是负数,因为一个数的偶数次方不可能为负数,所以要将答案一直除2,直到其为奇数
代码:
#include<iostream>
#include<string>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<queue>
#include<cstring>
#include<map>
using namespace std;
typedef long long ll;
#define M 66700
int c;
bool vis[M+10];
int prime[7000];
int gcd(int a,int b)
{
return b==0?a:gcd(b,a%b);
}
void init()
{
int m=sqrt(M+0.5);
int i,j;
c=0;
for(i=2;i<=m;i++)
{
if(!vis[i])
{
for(j=i*i;j<M;j+=i)
{
vis[j]=true;
}
}
}
for(i=2;i<M;i++)
{
if(!vis[i])
prime[c++]=i;
}
}
int main()
{
init();
int i;
ll n;
while(scanf("%lld",&n)&&n)
{
bool flag=true; //true 代表为正数
if(n<0)
{
n=-n;
flag=false;
}
int ans=0,num;
for(i=0;i<c&&n>1;i++)
{
if(n%prime[i]==0)
{
num=0;
while(n%prime[i]==0)
{
num++;
n=n/prime[i];
}
ans=gcd(ans,num);
}
}
if(n>1)
ans=gcd(ans,1);
if(flag)
printf("%d\n",ans);
else
{
while(ans%2==0)
{
ans=ans/2;
}
printf("%d\n",ans);
}
}
return 0;
}