import java.util.Scanner; public class GCD { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); int max = 1; for (int i = 2; i <= a; i++) { if (a % i == 0 && b % i == 0) { max = i; } } System.out.println(max); } }
另外一種解法:
import java.util.Scanner; public class GCD { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); int max; for (max = a; !(a % max == 0 && b % max == 0); max--) { } System.out.println(max); } }
來源:http://www.csie.ntnu.edu.tw/~u91029/GreatestCommonDivisor.html
沒有留言:
張貼留言