基础练习题

6 最大公约数和最小公倍数

2023-09-23  本文已影响0人  北极的大企鹅

      public class _006Deff {
 
      public static void main(String[] args) throws Exception {
          inout();
      }
  
      public static void inout() {
          Scanner scanner = new Scanner(System.in);
          while (true) {
             System.out.println("求最大公约数和最小公倍数 :");
             System.out.println("请输入一个数:");
             int a = scanner.nextInt();
             System.out.println("请输入另一个数:");
             int b = scanner.nextInt();
             count(a, b);
 
         }
     }

     private static void count(int x, int y) {
         _006Deff deff = new _006Deff();
         try {
             int m = deff.equals(x, y);
             int n = x * y / m;
             System.out.println("最大公约数是:" + m);
             System.out.println("最小公倍数是:" + n);

         } catch (Exception e) {
             throw new ArithmeticException("分母不能为零");
         }
     }
 
     public int equals(int x, int y) {
         int k;
         if (x < y) {
             k = x;
             x = y;
             y = k;
         }
 
         while (y != 0) {
             if (y == x) {
                 return x;
             } else {
                 int t = x % y;
                 x = y;
                 y = t;
             }
         }
         return x;
     }
 }
            
上一篇下一篇

猜你喜欢

热点阅读