算法: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);
        }
    }

}
复制代码

 

posted @   荒土  阅读(802)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示