TOJ 10009 GCD and LCM

題目鏈接 : TOJ10009


 

10009 - GCD and LCM

Time Limit: 1000MS
Memory Limit: 65536KB

Description
In mathematics, the greatest common divisor(GCD), sometimes known as the greatest common factor (GCF) or highest common factor (HCF), of two integers, is the largest positive integer that divides both numbers without remainder. The least common multiple(LCM) or lowest common multiple (LCM) or smallest common multiple(SCM) of two integers a and b is the smallest positive integer that is a multiple of both a and b.

In this problem, we define the GCD of an integer series as the largest positive integer that divides every number of that series without remainder. And the LCM of an integer series as the smallest positive integer that is a multiple of every number of the series.

For example, for the following integer series:

8 16 12 24

We have GCD = 4 and LCM = 48.

You are given an non-negative integer series, please calculate its GCD and LCM.


Input
The input will consist of a number of non-negative integers, one per line. Proceed to the end of input.



Output
Two integers, the series' GCD and LCM, separated by a single space. Our input guarantees the correct answer will never exceed 263-1.



Sample Input
8
16
12
24



Sample Output
4 48

 

歐幾里得算法

 

#include<cstdio>


long long gcd(long long a,long long b)
{
	long long c=a%b;
	while(c)
	{
		a=b;b=c;
		c=a%b;
	}
	return b;
}
int main()
{
	long long ans1=0,ans2=0,k,temp;
	while(scanf("%lld",&temp)==1)
	{
		if(ans1==0) 
		{
			ans1=temp;
			ans2=temp;
		}
		else 
		{
			ans1=gcd(ans1,temp);
			ans2=ans2/gcd(ans2,temp)*temp;
		}
	}
	printf("%lld %lld",ans1,ans2);
	return 0;
}


 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章