poj 1730Perfect Pth Powers(分解质因数)

                                                         Perfect Pth Powers

Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 16746 Accepted: 3799

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

题意:给出一个整数x,把x写成x=a^p,求p最大是多少?

分析:把x分解质因数,x = a1^b1 * a2^b2 … ak^bk,则最终结果为b1,b2,…bk的最大公约数。注意x有可能是负数。

如果x是负数,则要把求得的答案一直除以2,知道结果一个奇数,因为一个数的偶数次方不可能是负数。

#include <cstdio>
#include <cmath>
#include <cstring>

const int N = 66700;
int is[N];
int prime[7000], prime_cnt;

void get_prime() {   //筛法预处理出素数
    for(int i = 0; i < N; i++) is[i] = 1;
    is[0] = is[1] = 0;
    prime_cnt = 0;
    int m = (int)sqrt(N + 0.5);
    for(int i = 2; i < N; i++) {
        if(is[i]) {
            prime[prime_cnt++] = i;
            if(i <= m) {
                for(int j = i * i; j < N; j += i)
                    is[j] = 0;
            }
        }
    }
}

int gcd(int a, int b) { //求最大公约数
    if(a < b) return gcd(b, a);
    if(b == 0) return a;
    return gcd(b, a % b);
}

int main() {
    get_prime();
    long long n;  //不知道当n为int时为什么会TLE
    while(~scanf("%lld", &n) && n) {
        int flag = 0;
        if(n < 0) {
            flag = 1;
            n = -n;
        }
        int ans = 0;
        for(int i = 0; i < prime_cnt && n > 1; i++) {
            if(n % prime[i] == 0) {
                int cnt = 0;
                while(n % prime[i] == 0) {
                    n /= prime[i];
                    cnt++;
                }
                ans = gcd(ans, cnt);
            }
        }
        if(n > 1) ans = gcd(ans, 1); //如果n不为1,则此时的n必为是一个素数
        if(flag) {
            while(ans % 2 == 0) ans /= 2;
        }
        printf("%d\n", ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值