zoukankan      html  css  js  c++  java
  • 算法:x的n次方

    该题是用来公司教学,并无难度。用于说明算法效率差异以及循环和递归的效率差别。

    package practice;
    
    import java.math.BigDecimal;
    
    /**
     * @author caiyu
     * @date 2014-12-3
     */
    public class X_N_Square {
        static BigDecimal x = new BigDecimal(7);
    
        public static void main(String[] args) {
            int n = 1000;
            BigDecimal result = x;
    
            long time = System.currentTimeMillis();
            if (n < 5000)
                for (int i = 1; i < n; i++) {
                    result = result.multiply(x);
                }
            System.out.println(System.currentTimeMillis() - time);
    
            if (n < 5000)
                System.out.println(result);
    
            time = System.currentTimeMillis();
            result = cal(n, x);
            System.out.println(System.currentTimeMillis() - time);
    
            if (n < 5000)
                System.out.println(result);
    
            time = System.currentTimeMillis();
            // 换底公式
            int count = (int) Math.floor(Math.log(n) / Math.log(2));
            result = x;
            while (count-- > 0) {
                result = (n >> count) % 2 == 0 ? result.multiply(result) : result
                        .multiply(result).multiply(x);
            }
            System.out.println(System.currentTimeMillis() - time);
    
            if (n < 5000)
                System.out.println(result);
        }
    
        public static BigDecimal cal(int n, BigDecimal r) {
            if (n == 1)
                return x;
            if (n % 2 == 0) {
                r = cal(n / 2, r);
                return r.multiply(r);
            } else {
                r = cal((n - 1) / 2, r);
                return r.multiply(r).multiply(x);
            }
        }
    
    }
  • 相关阅读:
    android apk 反编译
    js 读 xml 非ie 可以支持 chrome 浏览器 与 android webView
    php+mySQl 环境搭建
    Activity 生命周期
    div 隐藏 显示 占空间 不占空间
    android 异步加载
    android 文件操作
    透明 GridView 背景透明
    eclipse 版本理解
    WebKit 上的JS直接使用Java Bean
  • 原文地址:https://www.cnblogs.com/anrainie/p/4139767.html
Copyright © 2011-2022 走看看