The least common multiple (LCM) of a set of positive integers is the smallest positive integer which is divisible by all the numbers in the set. For example, the LCM of 5, 7 and 15 is 105.
2 3 5 7 15 6 4 10296 936 1287 792 1
105 10296
虽然题目说求最小最大公约数,但其实是最小公倍数。需要用到辗转相除。
#include<iostream> #include<cstdio> using namespace std; int division(int a,int b); int lcm(int a,int b); int main() { int a[1000]; int n,i,j,length,sum; while(scanf("%d",&n)!=EOF) { for(i=0;i<n;i++) { cin>>length; for(j=0;j<length;j++) { cin>>a[j]; } sum=a[0]; for(j=0;j<length;j++) { sum=lcm(sum,a[j]); } cout<<sum<<endl; } } } int lcm(int a,int b) { return (a/division(a,b))*b;//求a和b的最小公倍数。 } int division(int a,int b) { if(b==0) { return a;//返回最小公约数 } else { return division(b,a%b); } }