Perfect Pth Powers
Time Limit: 1000MS Memory Limit: 10000K
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,使用pow进行运算会出现精度丢失问题,在这里要给pow计算出的结果加0.1,防止转int是舍去1
具体解释可以参考此贴[C/C++]C语言中math.h和cmath的pow()精度问题
2.会有负数,加一步特判,如果为负数,只能在进行pow()时使用奇数
这道题对我还有一个点是在写这道题时,由于英语垃圾,并没有看到范围在int内,所以不知道从31开始往下判断,卡了一下,还有就是对pow()运算不是很理解会用。。。
#include<stdio.h>
#include<math.h>
int main(){
int a = 1;
int b,mx = 0;
while(scanf("%d",&a)&&a!=0){
if(a > 0){
for(int i = 32;i >= 1;i--){
b = (int)(pow((double)a,1.0/i) + 0.1);//此处加0..1
if(a == int(pow((double)b,(double)i)+0.1)){//此处加0.1
mx = i;
break;
}
}
printf("%d\n",mx);
}
else{
a = -a;
for(int i = 31;i >= 1 ;i-=2){
b = (int)(pow((double)a,1.0/i) + 0.1);//同上
if(a == int(pow((double)b,(double)i)+0.1)){
mx = i;
break;
}
}
printf("%d\n",mx);
}
mx = 0;
}
return 0;
}