網頁

工商專區

2013年12月27日

找最大公因數

輸入兩數,找出兩數間的最大公因數



  1. import java.util.Scanner;
  2.  
  3. public class GCD {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. Scanner sc = new Scanner(System.in);
  8.  
  9. int a = sc.nextInt();
  10. int b = sc.nextInt();
  11. int max = 1;
  12.  
  13. for (int i = 2; i <= a; i++) {
  14. if (a % i == 0 && b % i == 0) {
  15. max = i;
  16. }
  17. }
  18.  
  19. System.out.println(max);
  20. }
  21. }





另外一種解法:
  1. import java.util.Scanner;
  2.  
  3. public class GCD {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. Scanner sc = new Scanner(System.in);
  8.  
  9. int a = sc.nextInt();
  10. int b = sc.nextInt();
  11. int max;
  12.  
  13. for (max = a; !(a % max == 0 && b % max == 0); max--) {
  14. }
  15.  
  16. System.out.println(max);
  17. }
  18. }

來源:http://www.csie.ntnu.edu.tw/~u91029/GreatestCommonDivisor.html

沒有留言:

張貼留言