POJ 1730 Perfect Pth Powers(最暴力 pow枚举)

博客围绕Perfect Pth Powers算法题展开,介绍了题目描述、输入输出要求及示例。同时指出该题的两个坑点,一是使用pow运算会有精度丢失问题,需给结果加0.1;二是存在负数情况,进行pow运算时只能用奇数。还分享了解题时遇到的问题。

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

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;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Randy__Lambert

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值