Perfect Pth Powers poj1730

本文介绍了一种算法,用于确定一个整数x的最大指数p,使得x为某个整数b的p次幂。通过质因数分解并计算各质因数的最高次幂,最终找出这些次幂数的最大公约数,即为所求的最大p值。
Perfect Pth Powers
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 16383 Accepted: 3712

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 pth power.

Sample Input

17
1073741824
25
0

Sample Output

1
30
2


 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstdio>
 4 #include <math.h>
 5 #define MAXN 100010
 6 #define INF 0x7fffffff
 7 using namespace std;
 8 const int N = 77000 ;
 9 int np[N >> 6], p[N >> 2],ans[N]= {0};
10 void init()
11 {
12     int n = N;
13     p[0] = 1, p[1] = 2;
14     for (int i = 3; i <= n; i++, i++)
15     {
16         if (np[i >> 6] & (1 << ((i >> 1) & 31))) continue;
17         p[++p[0]] = i;
18         for (int j = (i << 1) + i; j <= n; j += (i << 1))
19         {
20             np[j >> 6] |= (1 << ((j >> 1) & 31));
21         }
22     }
23 }
24 int gcd(int x,int y)
25 {
26     if(y==0)return x;
27     return gcd(y,x%y);
28 }
29 int fun(long long x)
30 {
31     int i,ans=0,an=0;
32     bool flag=0;
33     if(x<0)flag=1,x=-x;;
34     for(i=1; x>=p[i]&&i<=p[0]; i++)
35     {
36         if(x%p[i]==0)
37         {
38             ans=0;
39             while(x%p[i]==0)ans++,x/=p[i];
40             if(an==0)an=ans;
41             else
42             {
43                 an=gcd(ans,an);
44             }
45         }
46     }
47     if(x!=1)
48     {
49         an=1;
50     }
51     while(flag&&(an%2==0))an>>=1;
52     if(an==0)return 1;
53     return an;
54 }
55 int main()
56 {
57     init();
58     long long n;
59     while(~scanf("%I64d",&n),n)
60     {
61         printf("%d\n",fun(n));
62     }
63 }
View Code

 

转载于:https://www.cnblogs.com/ERKE/p/3690065.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值