• 最大公约和最小公倍数


    package basic40;

    import java.util.Scanner;

    public class CommonDivisor {
        public static int CommonDiv(int a, int b){
            int max = a > b ? a : b;
            int min = a < b ? a: b;
            while (max % min != 0){
                int temp = max % min;
                max = min;
                min = temp;
            }
            return min;
        }
        
        public static int CommonMultiple(int a, int b){
            int commonDivisor = CommonDiv(a, b);
            int aa = a / commonDivisor;
            int bb = b / commonDivisor;
            return commonDivisor * aa * bb;
        }
        
        public static void main(String args[]){
            Scanner sc = new Scanner (System.in);
            int a = sc.nextInt();
            int b = sc.nextInt();
            System.out.println( "CommonDivisor is:" + CommonDiv (a, b));
            System.out.println("CommonMultiple is:" + CommonMultiple(a, b));
            
        }
        
    }

    注意:

    1.一开始要判断输入的数的情况:若为负数;若有为0的数, 需要return -1

    2.求最大公约数更简便的写法:

    public static int gcd(int m, int n)

    {

    while (true)

    {

    if ((m = m % n) == 0)

    return n;

    if ((n = n % m) == 0)

    return m;

    }

    }

    3.最小公倍数的另一种求法

    a * b / c

    4.while(true)的用法:

    用法?问的好奇怪。while都是用来循环么。循环终止条件写true,这种情况,是需要在循环内主动终止循环的,要么使用return返回,要么使用break跳出循环
    用在哪里呢?比如socket连接,服务端就需要一直等到客户端输入啊响应啊这么样的。还有很多其他的情况呢。需要你慢慢去发掘。
  • 相关阅读:
    Iterator与 Enumeration
    多态性理解
    django---路由层
    django常用模块汇总
    django初识
    python常见模块
    python PEP8规范
    logging模块
    mysql一些了解的名词
    python 链接 mysql数据库
  • 原文地址:https://www.cnblogs.com/fthjane/p/4781280.html
Copyright © 2020-2023  润新知