POJ 1730 Perfect Pth Powers

M - Perfect Pth Powers
Time Limit:1000MS     Memory Limit:10000KB     64bit IO Format:%I64d & %I64u
Submit Status

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


此题解题思路:由于给定的数比较大,一一枚举计算量比较大,所以需要从另一个方面出发!由于给定的数不会超过某个数的32次方,那么我就可以从32次方往下枚举,以减少计算量,不过过程中需要再次优化!见代码中的解释
另外需要注意负数的情况!!!
 
解题代码:
View Code
 1 // File Name:b.cpp
 2 // Author: sheng
 3 // Created Time: 2013年04月02日 星期二 20时24分39秒
 4 
 5 #include <iostream>
 6 #include <stdio.h>
 7 #include <string.h>
 8 #include <math.h>
 9 using namespace std;
10 
11 typedef long long LL;
12 const double INF = 1e-7;//防止精度问题而导致的出错
13 
14 int main()
15 {
16     int i, flag;
17     LL n, temp;
18     while (~scanf ("%lld", &n) && n)
19     {
20         flag = 0;
21         if (n < 0)
22         {
23             flag = 1;
24             n = -n;
25         }
26         for (i = 32; i >=1; i --)//从32次方开始枚举
27         {
28             temp = (LL)(pow(n, 1./i) + INF);//计算n的 i 方跟,一次到位
29             if (pow(temp, i) == n && (!flag || (flag & i)))//判断temp的i次方是否与n==,并对负数情况进行处理
30                 break;
31         }
32         printf ("%d\n", i);
33     }
34     return 0;
35 }

 

 

posted on 2013-04-03 21:31  圣手摘星  阅读(152)  评论(0编辑  收藏  举报

导航