POJ1730 ZOJ2124 UVA10622 Perfect Pth Powers【快速幂+暴力】

509 篇文章 9 订阅
232 篇文章 0 订阅

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;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值