LightOJ 1220 Mysterious Bacteria【求质因子+gcd】

版权声明:转载什么的好说,附上友链就ojek了,同为咸鱼,一起学习。 https://blog.csdn.net/sodacoco/article/details/86586738

题目:

Dr. Mob has just discovered a Deathly Bacteria. He named it RC-01. RC-01 has a very strange reproduction system. RC-01 lives exactly xdays. Now RC-01 produces exactly p new deadly Bacteria where x = bp (where b, p are integers). More generally, x is a perfect pth power. Given the lifetime x of a mother RC-01 you are to determine the maximum number of new RC-01 which can be produced by the mother RC-01.

Input

Input starts with an integer T (≤ 50), denoting the number of test cases.

Each case starts with a line containing an integer x. You can assume that x will have magnitude at least 2 and be within the range of a 32 bit signed integer.

Output

For each case, print the case number and the largest integer p such that x is a perfect pth power.

Sample Input

3

17

1073741824

25

Sample Output

Case 1: 1

Case 2: 30

Case 3: 2

题目大意:

       给定x,寻找满足 x=b^p(b,p为整数)的p的最大值。

解题思路:

       原以为挺简单的一道题,死活过不了,看了题解才明白,一是没有考虑负数,而是我的暴力毫无技巧,而这是一道思维题。。

       例:给你一个数x = b^p,求p的最大值 

              x = p1^x1*p2^x2*p3^x3*...*ps^xs【数论--唯一分解定理】

              如果x = 12 = 2^2*3^1,要让x = b^p,及12应该是12 = 12^1

              所以p = gcd(x1, x2, x3, ... , xs);

              比如:24 = 2^3*3^1,p应该是gcd(3, 1) = 1,即24 = 24^1

                         324 = 3^4*2^2,p应该是gcd(4, 2) = 2,即324 = 18^2

               本坑:x可能为负数,如果x为负数的话,x = b^q, q 必须使奇数,所以将x转化为正数求得的如果是偶数的话,必须将其一直除2转化为奇数x= -16 = 16 = 2^4=4^2=16^1= -16 ^1。

实现代码:

#include<bits/stdc++.h>
using namespace std;
typedef int Int;
#define int long long

set<int>s;
void get_fac(int n){
    for(int i=2;i*i<=n;i++){
        int ans=0;
        if(n%i==0){ //每一位的上角标
            while(n%i==0) n/=i,ans++;
            s.insert(ans);
        }
    }
    if(n>1) s.insert(1);//未除尽的数,上角标默认为1
}
int gcd(int a,int b)    //求最大公因子
{
    return b==0?a:gcd(b,a%b);
}
Int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int t;
    cin>>t;
    for(int ca=1;ca<=t;ca++)
    {
        cout<<"Case "<<ca<<": ";
        int n;
        cin>>n;
        s.clear();
        
        get_fac(abs(n));
        if(s.size()==1){
            int ans=*s.begin();
            if(n<0){
                while(ans%2==0) ans/=2;
                cout<<ans<<endl;
            }
            else cout<<ans<<endl;
        }
        else{
            int ans=*s.begin();
            set<int>::iterator it;
            for(it=s.begin();it!=s.end();it++) ans=gcd(ans,*it);
            
            if(n<0) cout<<1<<endl;
            else cout<<ans<<endl;
        }
    }
    cin.get(),cin.get();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/sodacoco/article/details/86586738