2019年3月19日 星期二

JAVA經典程式題目-求最大公因數(遞迴 和 迴圈)

import java.util.Scanner;

public class GcdUseRecursion {

public static int gcd(int m, int n) {
if(n==0) {
return m;
}else {
return gcd(n,m%n);
}

}

public static int gcd2(int m, int n) {
int value=0;
while(n!=0) {
value = m%n;
m= n;
n= value;
}

return m;
}

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
        System.out.println("Please fill in :");
        System.out.print("m = ");
        int m =  scanner.nextInt();
        System.out.print("n = ");
        int n = scanner.nextInt();
        System.out.println("GCD: " + gcd(m, n));
        System.out.println("GCD2: " + gcd2(m, n));
}

}

沒有留言: