求n个数的最小公倍数

该博客介绍了如何通过递归算法解决求解n个数的最小公倍数问题。首先,计算前两个数的最小公倍数,然后以此替换原数列的这两个数,重复此过程直至数列只剩一个数,即为所有数的最小公倍数。文章以HDU 1019例题为背景进行阐述。

大致思路:每步将两个数替换成它们的最小公倍数,n-1 步后得到所有数的最小公倍数.

是先求最前面两个数的最小公倍数,再用这个数代替原数列中最前面的两个数,再算这一组数的最小公倍数,

是一个递归的算法,递归的结束条件是数列的长度为1。

即:

两个数的情况:
设两个数分别为a,b
先用辗转相除法求gcd(a,b),也就是a,b的最大公约数
然后lcm(a,b)=a*b/gcd(a,b)
n个数的情况:
设n个数分别为a1,a2,……an
则先求b1=lcm(a1,a2)
再求b2=lcm(b1,a3)
b3=lcm(b2,a4)
b4=lcm(b3,a5)
……
最后求到b[n-1]就是答案
复杂度接近O(n)

    //两个数的最大公约数--欧几里得算法
    int gcd(int a , int b ) {
	     if( !b ) return a ;
	     return gcd( b , a % b ) ;
    } 
      
    //n个数的最大公约数算法  
    //说明:   
    //把n个数保存为一个数组  
    //参数为数组的指针和数组的大小(需要计算的数的个数)  
    //然后先求出gcd(a[0],a[1]), 然后将所求的gcd与数组的下一个元素作为gcd的参数继续求gcd  
    //这样就产生一个递归的求ngcd的算法  
    int ngcd(int *a, int n )  
    {  
     if ( n == 1 )  
      return *a ;  
      
     return gcd(a[n-1] , ngcd(a, n-1 ) ) ;  
    }  
      
    //两个数的最小公倍数(lcm)算法  
    //lcm(a, b) = a / gcd(a, b) * b //防止a*b 溢出
    int lcm(int a, int b )  
    {  
         return a / gcd(a , b) * b ;  
    }  
      
    //n个数的最小公倍数算法  
    //算法过程和n个数的最大公约数求法类似  
    //求出头两个的最小公倍数,再将欺和大三个数求最小公倍数直到数组末尾  
    //这样产生一个递归的求nlcm的算法  
    int nlcm(int *a , int n )  
    {  
     if (n == 1)  
      return *a;  
     else  
      return lcm(a[n-1], nlcm(a, n-1 ) );  
    }  


例题:HDU - 1019

题目描述:

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.

Input
Input will consist of multiple problem instances. The first line of the input will contain a single integer indicating the number of problem instances. Each instance will consist of a single line of the form m n1 n2 n3 ... nm where m is the number of integers in the set and n1 ... nm are the integers. All integers will be positive and lie within the range of a 32-bit integer.

Output
For each problem instance, output a single line containing the corresponding LCM. All results will lie in the range of a 32-bit integer.

Sample Input
2
3 5 7 15
6 4 10296 936 1287 792 1
Sample Output
105
10296

代码:

#include<stdio.h>
#include<malloc.h>
typedef long long ll ;
ll *a ;  //统一数据类型 
ll gcd ( int n , int m ) {
	if( !m ) return n ;
	return gcd( m , n % m ) ;
}
ll lcm ( int n , int m ) {
	return n / gcd( n , m ) * m ;
}
ll nlcm ( ll *a , int n ) {
	if( n==1 ) return *a ;
	return lcm( a[n-1] , nlcm( a , n-1 ) );
}
int main() {
	int t , n ;
	scanf("%d" , &t ) ;
	while( t-- ) {
		scanf("%d" , &n ) ;
		a = ( ll* )malloc( sizeof( ll ) * (n) ) ;//开动态 
		for( int i=0 ; i<n ; i++ ) {
			scanf("%lld" , &a[i] ) ;
		}
		printf("%lld\n" , nlcm( a , n ) ) ;
	}
	return 0 ;
}



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值