poj - 1730 - Perfect Pth Powers - (分解质因数)

本文介绍了一种算法,用于找出整数x作为完美p次幂的最大指数p。通过分解质因数并利用最大公约数的方法来解决该问题。特别讨论了负数情况的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.
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 th power.
Sample Input
17
1073741824
25
0
Sample Output
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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值