本帖最後由 tonyh 於 2021-8-17 17:30 編輯
- import java.util.Scanner;
- public class Ch01 {
- public static void main(String[] args) {
- int x, y, smaller, gcd=0;
- Scanner s=new Scanner(System.in);
- System.out.print("請依序輸入兩個正整數: ");
- x=s.nextInt();
- y=s.nextInt();
- smaller=x<y?x:y;
- for(int i=1; i<=smaller; i++)
- if(x%i==0 && y%i==0)
- gcd=i;
- System.out.printf("%d與%d的最大公因數為: %d",x,y,gcd);
- }
- }
複製代碼- import java.util.Scanner;
- public class Ch01 {
- public static void main(String[] args) {
- int x, y, smaller, gcd=0;
- Scanner s=new Scanner(System.in);
- System.out.print("請依序輸入兩個正整數: ");
- x=s.nextInt();
- y=s.nextInt();
- smaller=x<y?x:y;
- for(int i=smaller; i>=1; i--)
- {
- if(x%i==0 && y%i==0)
- {
- gcd=i;
- break;
- }
- }
- System.out.printf("%d與%d的最大公因數為: %d",x,y,gcd);
- }
- }
複製代碼- import java.util.Scanner;
- public class Ch01 {
- public static void main(String[] args) {
- int x, y;
- Scanner s=new Scanner(System.in);
- System.out.print("請依序輸入兩個正整數: ");
- x=s.nextInt();
- y=s.nextInt();
- System.out.printf("%d與%d的最大公因數為: %d",x,y,gcd(x,y));
- }
-
- static int gcd(int x, int y)
- {
- while(x%y!=0)
- {
- int tmp=x%y;
- x=y;
- y=tmp;
- }
- return y;
- }
- }
- /* x y x%y
- 56 / 35 = 1 ... 21
- 35 / 21 = 1 ... 14
- 21 / 14 = 1 ... 7
- 14 / 7 = 2 ... 0
- */
複製代碼- import java.util.Scanner;
- public class Ch01 {
- public static void main(String[] args) {
- int x, y;
- Scanner s=new Scanner(System.in);
- System.out.print("請依序輸入兩個正整數: ");
- x=s.nextInt();
- y=s.nextInt();
- System.out.printf("%d與%d的最大公因數為: %d",x,y,gcd(x,y));
- }
-
- static int gcd(int x, int y)
- {
- if(x%y==0)
- return y;
- else
- return gcd(y, x%y);
- }
- }
- /* x y x%y
- 56 / 35 = 1 ... 21
- 35 / 21 = 1 ... 14
- 21 / 14 = 1 ... 7
- 14 / 7 = 2 ... 0
- */
複製代碼 |