zoukankan      html  css  js  c++  java
  • 几个基本数学问题

    分解质因数

    求最大公约数

    求最小公倍数

    牛顿迭代求平方根

    分解质因数

    import java.util.ArrayList;
    import java.util.List;
    
    public class Solution {
    
        // 返回质因数分解
        List<Integer> getPrimeFactors(int n) {
            List<Integer> list = new ArrayList<Integer>();
            for (int i = 2; i <= n; i++) {
                // 注意while的终止条件是n!=i
                while (n != i) {
                    if (n % i == 0) {
                        list.add(i);
                        n = n / i;
                    } else
                        break;
                }
            }
            list.add(n);
            return list;
    
        }
    
        public static void main(String[] args) {
            System.out.println(new Solution().getPrimeFactors(120));
    
        }
    }

    求最大公约数

    public class Solution {
        /**
         * 辗转相除法 缺点:对于大整数求模是瓶颈
         */
        public int gcd1(int x, int y) {
            return y == 0 ? x : gcd1(y, x % y);
        }
    
        /**
         * 更相减损术 缺点:某些case下递归次数太多,不如gcd(100000,1)的情况。
         */
        public int gcd2(int x, int y) {
            if (x < y)
                return gcd2(y, x);
            if (y == 0)
                return x;
            else
                return gcd2(x - y, y);
    
        }
    
        /**
         * 编程之美上的方法,避免了以上两种方法的劣势, 复杂度O(log(max(x,y)));
         */
        public int gcd(int x, int y) {
            if (x < y)
                return gcd(y, x);
            if (y == 0)
                return x;
            else {
                if (isEven(x)) {
                    if (isEven(y)) {
                        return gcd(x >> 1, y >> 1) << 1;
                    } else {
                        return gcd(x >> 1, y);
                    }
    
                } else {
                    if (isEven(y)) {
                        return gcd(x, y >> 1);
                    } else {
                        return gcd(y, x - y);
                    }
    
                }
    
            }
    
        }
    
        private boolean isEven(int x) {
            return (x & 1) == 0;
        }
    
        public static void main(String[] args) {
            int a = 420000, b = 3050;
            System.out.println(new Solution().gcd1(a, b));
            System.out.println(new Solution().gcd2(a, b));
            System.out.println(new Solution().gcd(a, b));
    
        }
    }

    求最小公倍数

    x*y/gcd(x,y);

    牛顿迭代求平方根

    http://blog.csdn.net/sjf0115/article/details/8607378 

  • 相关阅读:
    RAID实战案例
    文件系统常用工具实战篇
    挂载文件系统
    硬盘结构类型概述
    创建文件系统实战篇
    JumpServer的会话管理及命令过滤器应用案例
    JumpServer的权限管理
    JumpServer的用户管理
    helm基础
    hpa控制器
  • 原文地址:https://www.cnblogs.com/jdflyfly/p/3977593.html
Copyright © 2011-2022 走看看