返回列表 發帖
  1. import java.util.Scanner;
  2. public class Ch05
  3. {
  4.         public static void main(String[] args)
  5.         {
  6.             Scanner s=new Scanner(System.in);
  7.             int x,y,smaller,g=0;
  8.             System.out.print("請依序輸入兩個正整數:");
  9.             x=s.nextInt();
  10.             y=s.nextInt();
  11.             smaller=x<y?x:y;
  12.             for(int i=1;i<=smaller;i++)
  13.             {
  14.                     if(x%i==0 && y%i==0)
  15.                             g=i;
  16.             }
  17.             System.out.printf("%d與%d的最大公因數為:%d",x,y,g);
  18.         }
  19. }
複製代碼

TOP

  1. import java.util.Scanner;
  2. public class Ch05
  3. {
  4.         public static void main(String[] args)
  5.         {
  6.             Scanner s=new Scanner(System.in);
  7.             int x,y,smaller,g=0;
  8.             System.out.print("請依序輸入兩個正整數:");
  9.             x=s.nextInt();
  10.             y=s.nextInt();
  11.             smaller=x<y?x:y;
  12.             for(int i=smaller; i>=1; i--)
  13.         {
  14.             if(x%i==0 && y%i==0)
  15.             {
  16.                 g=i;
  17.                 break;
  18.             }
  19.         }
  20.             System.out.printf("%d與%d的最大公因數為:%d",x,y,g);
  21.         }
  22. }
複製代碼

TOP

  1. import java.util.Scanner;
  2. public class Ch05
  3. {
  4.         public static void main(String[] args)
  5.         {
  6.             Scanner s=new Scanner(System.in);
  7.             int x,y;
  8.             System.out.print("請依序輸入兩個正整數:");
  9.             x=s.nextInt();
  10.             y=s.nextInt();
  11.             System.out.printf("%d與%d的最大公因數為:%d",x,y,g(x,y));
  12.         }
  13.         static int g(int x,int y)
  14.         {
  15.                 while(x%y!=0)
  16.                 {
  17.                         int t=x%y;
  18.                         x=y;
  19.                         y=t;
  20.                 }
  21.                 return y;
  22.         }
  23. }
複製代碼

TOP

  1. import java.util.Scanner;
  2. public class Ch05
  3. {
  4.         public static void main(String[] args)
  5.         {
  6.             Scanner s=new Scanner(System.in);
  7.             int x,y;
  8.             System.out.print("請依序輸入兩個正整數:");
  9.             x=s.nextInt();
  10.             y=s.nextInt();
  11.             System.out.printf("%d與%d的最大公因數為:%d",x,y,g(x,y));
  12.         }
  13.         static int g(int x,int y)
  14.         {
  15.                 if(x%y==0)
  16.                 {
  17.                         return y;
  18.                 }
  19.                 else
  20.                     return g(y,x%y);
  21.         }
  22. }
複製代碼

TOP

返回列表