light_oj 1220 素数分解

light_oj 1220  素数分解

J - Mysterious Bacteria
Time Limit:500MS     Memory Limit:32768KB     64bit IO Format:%lld & %llu

Description

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 x days. 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,找出最大的p使x=b^p;

思路:素数分解。x=(p1^k1)*(p2^k2)*...*(pn^kn) = (p1^a1*p2^a2*...*pn^an)^p=b^p,即提出来一个最大的p,p=gcd(k1,k2,...,kn)。

注意点:素数分解时由于素数表只能到10^7,所以需要对最后一个因子进行特判。

坑点:x为负数的时候p不能为偶数,这时只要把之前提出来的所有2都乘进去即可,剩下留在外面的奇数p就是答案了。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<vector>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<string>
#include<math.h>
#include<cctype>

using namespace std;

typedef long long ll;
const int maxn=10001000;
const int INF=(1<<29);
const double EPS=0.0000000001;
const double Pi=acos(-1.0);

ll x,p;
bool isprime[maxn];
vector<ll> prime;

void play_prime()
{
    memset(isprime,1,sizeof(isprime));
    isprime[1]=0;
    for(int i=2;i<maxn;i++){
        if(!isprime[i]) continue;
        for(int j=i+i;j<maxn;j+=i){
            isprime[j]=0;
        }
    }
    for(int i=1;i<maxn;i++){
        if(isprime[i]) prime.push_back(i);
    }
}

int main()
{

    int T;cin>>T;
    play_prime();
    int tag=1;
    while(T--){
        cin>>x;
        bool f=0;
        if(x<0) f=1,x=-x;
        p=-1;
        bool flag=1;
        for(int i=0;i<(int)prime.size()&&prime[i]*prime[i]<=x;i++){
            if(x%prime[i]) continue;
            ll k=0;
            while(x%prime[i]==0){
                x/=prime[i];
                k++;
            }
            if(p==-1) p=k;
            else p=__gcd(p,k);
        }
        if(x!=1) p=1;
        if(f){
            while(p%2==0) p/=2;
        }
        cout<<"Case "<<tag++<<": "<<p<<endl;
    }
    return 0;
}
View Code
没有AC不了的题,只有不努力的ACMER!
原文地址:https://www.cnblogs.com/--560/p/4564430.html