100c之42:最大公约数和最小公倍数

Table of Contents

问题

最大公约数和最小公倍数,求任意两个正整数的最大公约数和最小公倍数。

分析

假设两个数是a和b,用辗转相除法求得最大公约数。

程序

 1:  /**
 2:   * @file   042c.c
 3:   * @author Chaolong Zhang <emacsun@163.com>
 4:   * @date   Fri Jun 28 14:05:57 2013
 5:   * 
 6:   * @brief  最大公约数和最小公倍数,求任意两个正整数的最大公约数和最小公倍数。
 7:   * 
 8:   * 
 9:   */
10:  
11:  #include <stdio.h>
12:  
13:  int get_gcd( int,int );
14:  int get_lsm( int,int,int );
15:  
16:  int main(int argc, char *argv[])
17:  {
18:      int num1,num2,gcd,lsm;
19:  
20:      printf ("please input the two numbers:
");
21:      scanf( "%d,%d", &num1,&num2 );
22:      gcd=get_gcd( num1,num2 );
23:      lsm=get_lsm( num1,num2,gcd );
24:      printf ("the gcd of %d and %d is %d
",num1, num2,gcd);
25:      printf ("the lsm of %d and %d is %d
",num1, num2,lsm);
26:      return 0;
27:  }
28:  
29:  int get_gcd( int num1, int num2 ){
30:      int temp;
31:      if (num1<num2){
32:          temp=num1;
33:          num1=num2;
34:          num2=temp;
35:      }
36:      while( num2 ){
37:          temp=num1%num2;
38:          num1=num2;
39:          num2=temp;
40:      }
41:      return num1;
42:  }
43:  
44:  int get_lsm( int num1,int num2, int gcd ){
45:      return gcd*( num1/gcd )*( num2/gcd );
46:  }

结果

6,4
the gcd of 6 and 4 is 2
the lsm of 6 and 4 is 12
原文地址:https://www.cnblogs.com/chaolong/p/3160840.html