2017-11-08

Program:

  求两个数的最大公约数和最小公倍数(递归实现)

代码如下:

 1 package test;
 2 
 3 
 4 public class TestDemo {
 5     
 6     public static void main(String args[]) {
 7         
 8         int num1 = 12;            //数值1
 9         int num2 = 16;            //数值2
10         int maxCommon = 0;        //最大公约数
11         
12         maxCommon = getMaxCommon(num1,num2);
13         
14         System.out.println( num1 + "和" + num2 + "的最大公约数为:" + maxCommon );
15         System.out.println( num1 + "和" + num2 + "的最小公倍数为:" + (num1 * num2 / maxCommon) );
16 
17     }
18     
19     
20     /*
21      * 利用递归求解最大公约数和最小公倍数
22      * */
23     public static int getMaxCommon(int num1,int num2) {
24         
25         if( num2 == 0 ) {        //递归结束条件:num2(取余后的值)为0,即此时的num1(上一层递归的除数)为最大公约数
26             
27             return num1;         //返回被除数
28         }else {
29             
30             return getMaxCommon(num2, num1 % num2);        //递归
31         }
32     }
33     
34 }
原文地址:https://www.cnblogs.com/caizhen/p/7803427.html