POJ 1730 Perfect Pth Powers(暴力枚举)

题目链接:

https://cn.vjudge.net/problem/POJ-1730

题目描述:

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
 1 /*
 2 题意描述
 3 输入x,计算并输出满足x=b的p次方中最大的p
 4 
 5 解题思路
 6 因为x的大小为2到2的31次方,故可采取枚举次方的方法,计算出b,再计算出b的p次方为temp,看temp和x是否相等即可。
 7 另外需要注意的是x可能为负数,首先需要将负数变为正数,另外枚举的时候只能枚举奇数次方,因为偶数次方不能的到负数。
 8 另外是用pow开方和乘方时注意精度问题,比如4.999999直接取整误差很大,加上0.1即可避免此类问题。 
 9 */
10 #include<cstdio>
11 #include<cmath>
12 
13 int main()
14 {
15     int x;
16     while(scanf("%d",&x),x != 0){
17         if(x > 0){
18             for(int i=31;i>=1;i--){
19                 int b=(int)(pow(x*1.0,1.0/(i*1.0)) + 0.1); 
20                 int temp=(int)(pow(b*1.0,i*1.0) + 0.1);
21                 if(x == temp){
22                     printf("%d\n",i);
23                     break;
24                 }
25             }
26         }
27         else{
28             x *= -1;
29             for(int i=31;i>=1;i-=2){
30                 int b=(int)(pow(x*1.0,1.0/(i*1.0)) + 0.1); 
31                 int temp=(int)(pow(b*1.0,i*1.0) + 0.1);
32                 if(x == temp){
33                     printf("%d\n",i);
34                     break;
35                 }
36             }
37         }
38     }
39     return 0;
40 } 

猜你喜欢

转载自www.cnblogs.com/wenzhixin/p/9338116.html