121】Finding LC M【算數基本定理】
LCM is an abbreviation used for Least Common Multiple in Mathematics. We say LCM (a, b, c) = L if and only if L is the least integer which is divisible by a, b and c.
You will be given a, b and L. You have to find c such that LCM (a, b, c) = L. If there are several solutions, print the one where c is as small as possible. If there is no solution, report so.
Input
Input starts with an integer T (≤ 325), denoting the number of test cases.
Each case starts with a line containing three integers a b L (1 ≤ a, b ≤ 106, 1 ≤ L ≤ 1012).
Output
For each case, print the case number and the minimum possible value of c. If no solution is found, print ‘impossible’.
Sample Input
3
3 5 30
209475 6992 77086800
2 6 10
Sample Output
Case 1: 2
Case 2: 1
Case 3: impossible
程式碼
#include<bits/stdc++.h>
using namespace std;
#define LL long long
const int N = (int)1e6+2;
const int M = 1E6+11;
const int mod = 1e9+7;
const int inf = 0x3f3f3f3f;
bool su[N+1]={1 ,1,0};int prm[N+1],sz=0;
void init(){
for(LL i=2;i<N;i++){
if(!su[i]){
prm[sz++]=i;
for(LL j=i*i;j<N;j+=i)
su[j]=1;
}
}
// cout<<sz<<endl;;
}
int a[N],b[N];
void solve(int *arr,int n){
for(int i=0;i<sz ;i++){
while(n%prm[i]==0){
arr[i]++;
n/=prm[i];
}
if(n==1) break;
}
}
int main(){
init();
int cas=1;
int T;scanf("%d",&T);
while(T--){
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
LL A,B,L;scanf("%lld%lld%lld",&A,&B,&L);
solve(a,A);
solve(b,B);
LL ans=1; int flag=1;
for(int i=0;i<sz;i++){
int cnt=0;
while(L%prm[i]==0){
cnt++; L/=prm[i];
}
if(a[i]>cnt || b[i]>cnt) {
flag=0; break;
}
if(a[i]==cnt ||b[i]==cnt) continue;
ans*=pow(prm[i],cnt);
}
if(L!=1) ans*=L;
printf("Case %d: ",cas++);
if(flag) printf("%lld\n",ans);
else puts("impossible");
}
return 0;
}