做题链接
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.
这道题若果有一般的方式去做,肯定会时间超限,所以只能想其他的办法,其中一个方法就是,输入一个数x,设两个整数t、m,另t等于x开p次方,而m等于t的p次方,若m==x,则输出p的值(p从31开始减1);但当x是负数时,由于数据只限于实数范围内,所以x肯定不能开偶次方。
#include<stdio.h>
#include<math.h>
int x,i,m,t;
int main(){
while(~scanf("%d",&x) && x){//当输入的x的值为零时,结束
if(x>0){
for(int i=31;i>0;i--){//因为输入的数据是在int范围内,所以i从31开始。
t = floor(pow(x*1.0,1.0/i)+0.001);//floor函数取整。因为pow函数计算的精度问题,加上0.0001后不会出错
m = floor(pow(t*1.0,1.0*i)+0.001);
if(m == x){
printf("%d\n",i);
break;
}
}
}
else{
x =- x;//若x为负数,将它变成正数
for(int i = 31; i > 0;i -= 2){//因为负数不能开偶次方根,所以每次递减2
t = floor(pow(x*1.0,1.0/i)+0.001);
m = floor(pow(t*1.0,1.0*i)+0.001);
if(x == m){
printf("%d\n",i);
break;
}
}
}
}
return 0;
}
不得不说,这些题考得都是思维能力啊,有些看起来很难得问题当看到大神的思路时真是觉得这些题好简单啊!