1. 程式人生 > >最小公倍數和最大公約數

最小公倍數和最大公約數

n) 大於 != 公約數 rgs 不用 AI pre public

最近做到一個 分核桃的題。原題描述如下,就是一個求最小公倍數的題。這個知識點已經忘了。。就去百度查了一下,就有了這一篇總結。

技術分享圖片

這個是百度上的定義。

技術分享圖片

技術分享圖片

另外一個很重要的點 就是:最小公倍數=x*y/最大公約數;所以重點就轉到了求最大公約數上。最大公約數可以用以下三種方法:輾轉相除法,更相折損法(相減法),窮舉法。代碼如下。

 1 import java.util.Scanner;
 2 
 3 
 4 public class 最小公倍數{
 5     public static void main(String[] args) {
 6         Scanner in = new Scanner(System.in);
7 System.out.print("input x :"); 8 int x = in.nextInt(); 9 System.out.print("input y :"); 10 int y = in.nextInt(); 11 12 int z = Method(x,y); 13 System.out.println("輾轉相除法:"); 14 System.out.println("divisor : "+z); 15 System.out.println("multiple : "+(x*y/z));
16 17 System.out.println("相減法:"); 18 z = Subtraction(x,y); 19 System.out.println("divisor : "+z); 20 System.out.println("multiple : "+(x*y/z)); 21 22 System.out.println("窮舉法:"); 23 z = divisor(x,y); 24 System.out.println("divisor : "+divisor(x,y));
25 z=multiple(x,y); 26 System.out.println("multiple : "+multiple(x,y)); 27 } 28 29 //輾轉相除法:返回公約數 30 public static int Method(int x,int y){ 31 int a,b,c; 32 a=x; 33 b=y; 34 while(b!=0){ 35 c=a%b; 36 a=b; 37 b=c; 38 } 39 return a; 40 } 41 //相減法 42 public static int Subtraction(int x,int y){ 43 while(x!=y){ 44 if(x>y){ 45 x=x-y; 46 } 47 else{ 48 y=y-x; 49 } 50 } 51 return x; 52 } 53 //窮舉法 求公約數 54 public static int divisor(int x,int y){ 55 int z; 56 for(z=x;z>0;z--){ 57 if(x%z==0&&y%z==0){ 58 break; 59 } 60 } 61 return z; 62 } 63 //求公倍數 64 public static int multiple(int x,int y){ 65 int z; 66 for(z=x;;z++){ 67 if(z%x==0&&z%y==0){ 68 break; 69 } 70 } 71 return z; 72 } 73 74 }

回到分核桃的題,因為是三個數,所以我用了窮舉法求,其實用窮舉就不用求公約數了直接公倍數就好。代碼如下:

 1 import java.util.Arrays;
 2 import java.util.Scanner;
 3 
 4 public class 核桃數量 {
 5     public static int ICD(int a,int b,int c){
 6         int k=getMax(a,b,c);
 7         for(int i=k;;i++){
 8             if(i%a==0 && i%b==0 && i%c==0){
 9                 return i;
10             }
11         }
12         
13     }
14     public static int getMax(int a,int b,int c){
15         int aa[]={a,b,c};
16         Arrays.sort(aa);
17         return aa[2];
18     }
19     public static void main(String[] args) {
20         Scanner sc=new Scanner(System.in);        
21         int a=sc.nextInt();
22         int b=sc.nextInt();
23         int c=sc.nextInt();
24         System.out.println(ICD(a,b,c));
25     }
26 
27 }

然後看筆記上之前還有寫段關於最大的最小公倍數:

1.大於1的兩個相鄰自然數必定互質=》公約數只有1的兩個整數。

2.兩個數的最小公倍數在最大情況就是當兩個數互質時候,即為兩數的乘積。

最小公倍數和最大公約數