Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 18333 | Accepted: 4222 |
Description
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
Source
问题链接:POJ1730 ZOJ2124 UVA10622 Perfect Pth Powers
问题简述:(略)
问题分析:
这个程序采用暴力法进行计算,是合成法,为了加快计算速度使用了快速幂函数。
另外一种计算方法是对输入的x进行分解子因子的方法。
程序说明:(略)
题记:没有方法就用暴力法或模拟法。
参考链接:(略)
AC的C++语言程序如下:
/* POJ1730 ZOJ2124 UVA10622 Perfect Pth Powers */
#include <iostream>
#include <stdio.h>
#include <math.h>
using namespace std;
typedef long long LL;
// 快速幂
inline LL quickpow(LL x, LL n)
{
LL result = 1;
for(; n; n>>=1) {
if(n & 1)
result *= x;
x *= x;
}
return result;
}
int main()
{
LL x, px, ans;
while(~scanf("%lld", &x) && x) {
bool flag = false;
px = x < 0 ? -x : x;
for(int i=2; i<=floor(sqrt(px)) && !flag; i++) {
for(int j=2; ; j++) {
LL t = quickpow(i, j);
if(t > px)
break;
if(t == px && (x > 0 || (x < 0 && (j % 2 == 1)))) {
flag = true;
ans = j;
break;
}
}
}
printf("%lld\n", flag ? ans : 1);
}
return 0;
}