1. 程式人生 > >LightOj 1215 Finding LCM

LightOj 1215 Finding LCM

name nta put 們的 tro printf using con 所有

Discription

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

本來感覺這個題太水了就不想寫博客了2333,但是考慮到我馬上要做的那個題可能要用到這個題 一個東西,所以還是寫一下。

可以先求出lcm(a,b)=p,然後本質就是求一個 最小的 X 使得 lcm(X,p) = L。

無解很好判,只要p不是L的約數就無解。

考慮到lcm是對指數取max,而我們的目的是讓X最小,所以我們可以讓X在p和L次數相同的質因子上的次數取0,而在其他的質因子上取L在這上面的次數。

所以我們可以直接對 L/p 質因子分解, 然後 這裏的質因子就是所有X要和L次數一樣的質因子,只要把p和L/p在這上面的指數加起來就好啦。

#include<bits/stdc++.h>
#define ll unsigned long long
using namespace std;
int T,d[100],num=0;
ll a,b,L,ans=1;

ll gcd(ll x,ll y){
	return y?gcd(y,x%y):x;
}

inline void dvd(ll x){
	for(int i=2;i*(ll)i<=x;i++) if(!(x%i)){
		d[++num]=i;
		
		ll pre=x;
		while(!(x%i)) x/=i;
		ans*=pre/x;
		
		if(x==1) break;
	}
	if(x!=1) d[++num]=x,ans*=x;
}

inline void solve(){
	for(int i=1;i<=num;i++){
		ll pre=a;
		while(!(a%d[i])) a/=d[i];
		ans*=pre/a;
	}
	printf("%llu\n",ans);
}

int main(){
	scanf("%d",&T);
	for(int i=1;i<=T;i++){
		scanf("%llu%llu%llu",&a,&b,&L);
		a=a*b/gcd(a,b);
		printf("Case %d: ",i);
		
		num=0,ans=1;
		if(L%a) puts("impossible");
		else{
			dvd(L/a);
			solve();
		}
	}
	
	return 0;
}

  

LightOj 1215 Finding LCM