zoukankan      html  css  js  c++  java
  • 6 最大公约数和最小公倍数

    题目:输入两个正整数m和n,求其最大公约数和最小公倍数。
    * 代码分析:在循环中,只要除数不等于0,用较大数除以较小的数,
    * 将小的一个数作为下一轮循环的大数,取得的余数作为下一轮循环的较小的数,
    * 如此循环直到较小的数的值为0,返回较大的数,
    *此数即为最大公约数,最小公倍数为两数之积除以最大公约数。

     1      public class _006Deff {
     2 
     3     public static void main(String[] args) throws Exception {
     4         inout();
     5     }
     6 
     7     public static void inout() {
     8         Scanner scanner = new Scanner(System.in);
     9         while (true) {
    10             System.out.println("求最大公约数和最小公倍数 :");
    11             System.out.println("请输入一个数:");
    12             int a = scanner.nextInt();
    13             System.out.println("请输入另一个数:");
    14             int b = scanner.nextInt();
    15             count(a, b);
    16 
    17         }
    18     }
    19 
    20     private static void count(int x, int y) {
    21         _006Deff deff = new _006Deff();
    22         try {
    23             int m = deff.equals(x, y);
    24             int n = x * y / m;
    25             System.out.println("最大公约数是:" + m);
    26             System.out.println("最小公倍数是:" + n);
    27         } catch (Exception e) {
    28             throw new ArithmeticException("分母不能为零");
    29         }
    30     }
    31 
    32     public int equals(int x, int y) {
    33         int k;
    34         if (x < y) {
    35             k = x;
    36             x = y;
    37             y = k;
    38         }
    39 
    40         while (y != 0) {
    41             if (y == x) {
    42                 return x;
    43             } else {
    44                 int t = x % y;
    45                 x = y;
    46                 y = t;
    47             }
    48         }
    49         return x;
    50     }
    51 }
    52            
  • 相关阅读:
    责任链模式
    状态模式
    命令模式
    策略模式
    迭代器模式
    适配器模式
    装饰模式
    合成模式
    brew php 提示
    sarafi浏览器iframe跨域cookie无效的处理方案(笨方法,看官莫笑)
  • 原文地址:https://www.cnblogs.com/liuyangfirst/p/6502711.html
Copyright © 2011-2022 走看看