• 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 = 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

    题意:给出一个整数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
    ", ans);
        }
        return 0;
    }


  • 相关阅读:
    关于对话框创建与销毁的虚函数用法
    控件属性设置注意事项
    删除非空文件夹下所有内容方法
    CString类使用技巧
    视图间通信方法
    CTreeCtrl控件使用技巧
    MFC MDI 遍历打开的所有文档
    将datagrid的数据源到出导excel
    ASP.NET 給一組控件賦值 範例.
    ASP.NET Resouce Kit
  • 原文地址:https://www.cnblogs.com/tlnshuju/p/7141649.html
Copyright © 2020-2023  润新知