LightOJ-1220 Mysterious Bacteria (素数打表+欧几里得算法+唯一分解定理)给出x,求x=a^p,最大的指数
題目大意:
x = b^p, x只有一個因子的p次冪構成
如果24 = 2^3*3^1,p應該是gcd(3, 1) = 1,即24 = 24^1
324 = 3^4*2^2=(3^2*2)^2,p應該是gcd(4, 2) = 2,即324 = 18^2
所以p = gcd(x1, x2, x3, ... , xn){歐幾里得算法求取最大公約數};
*本題有一個坑,就是x可能為負數,如果x為負數的話,x = b^q, q必須使奇數,所以將x轉化為正數求得的解如果是偶數的話必須將其一直除2轉化為奇數
題目:
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
AC代碼:
#include<iostream> #include<string.h> typedef long long ll; #include<stdio.h> using namespace std; #define M 1000010 int dp[M]; int book[M]; int t,k; ll m; void dfs() {k=0;memset(dp,0,sizeof(dp));memset(book,0,sizeof(book));for(int i=2; i<M; i++)/**因為任何一個整數都可以由一個素數經過乘法運算得到,故可通過素數打表的方式求得某數的唯一分解(得到冪次最大)*/if(!book[i]){dp[k++]=i;/*記錄素數*/for(int j=2; i*j<M; j++)book[j*i]=1;} } int gcd(int a,int b) {return !b?a:gcd(b,a%b); } int main() {cin>>t;int tt=1;dfs();while(t--){int flag=0;cin>>m;if(m<0)/**本題的坑:m可能為負數*/{flag=1;m=-m;}int ans=0;for(int i=0;i<k&&dp[i]*dp[i]<=m;i++)/**care:remember停止條件為i<k&&dp[i]*dp[i]<=m,缺一不可*/{if(m%dp[i]==0){int a=0;while(m%dp[i]==0){m/=dp[i];/**唯一分解定理:直接對m的值進行操作,得到x=a1^b1*a2^b2.....an^bn*/a++;}if(ans=0)ans=a;elseans=gcd(ans,a);/**歐幾里得算法:求得到的素數的冪次進行求取最大公約數操作*/}if(m==1)break;}if(m>1)/**則m為素數,因數只有1和自身*/ans=1;if(flag)/**填坑:若為負數,冪次不可能為偶數,故由最大公約數求出最大的奇數*/{while(ans%2==0)ans/=2;}printf("Case %d: %d\n",tt++,ans);}return 0; }?
總結
以上是生活随笔為你收集整理的LightOJ-1220 Mysterious Bacteria (素数打表+欧几里得算法+唯一分解定理)给出x,求x=a^p,最大的指数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 流放之路召唤师最强BD
- 下一篇: 拓展欧几里得小结(初级理解)