Java、GCD的执行时间

package algorithm;

import java.math.BigInteger;

/**
 * @author: xyz
 * @create: 2022/8/12
 * @Description:
 * @FileName: Exercise22_06
 * @History:
 * @自定义内容:
 */
public class Exercise22_06 {
    public static void main(String[] args) {
        BigInteger[] fab = new BigInteger[5];
        for (int i = 41, j = 0; i <= 45; i++, j++)  //获取斐波那契数
            fab[j] = fab(i);

        long startTime = System.currentTimeMillis();
        System.out.println("\t\t\t\t\t\40\t\t41\t\t42\t\t43\t\t44\t\t45");
        System.out.print("程序清单22.3GCD\t\t\t\t\t");
        for (int i = 0; i < fab.length - 1; i++)
            System.out.print(gcd22_3(fab[i], fab[i + 1]) + "\t\t");
        long endTime = System.currentTimeMillis();
        long executionTime = endTime - startTime;
        System.out.println("\t执行时间:" + executionTime);

        startTime = System.currentTimeMillis();
        System.out.print("程序清单22.4GCDEuclid\t\t\t");
        for (int i = 0; i < fab.length - 1; i++)
            System.out.print(gcd22_4(fab[i], fab[i + 1]) + "\t\t");
        endTime = System.currentTimeMillis();
        executionTime = endTime - startTime;
        System.out.println("\t执行时间:" + executionTime);
    }

    /** 程序清单22.3GCD */
    public static BigInteger gcd22_3(BigInteger m, BigInteger n) {
        BigInteger gcd = BigInteger.ONE;

        //m % n == 0,返回n
        if (m.mod(n).equals(BigInteger.ZERO)) return n;

        //从n / 2开始,查找第一个能被m和n同时整除的数k
        for (BigInteger k = n.divide(BigInteger.valueOf(2)); k.compareTo(
                BigInteger.ZERO) > 0; k = k.subtract(BigInteger.ONE)) {
            if (m.mod(k).equals(BigInteger.ZERO) && n.mod(k).equals(BigInteger.ZERO)) {
                gcd = k;
                break;
            }
        }

        return gcd;
    }

    /** 程序清单22.4GCDEuclid */
    public static BigInteger gcd22_4(BigInteger m, BigInteger n) {
        return m.mod(n).equals(BigInteger.ZERO) ? n : gcd22_4(n, m.mod(n));
    }

    /** 返回斐波那契数 */
    public static BigInteger fab(long index) {
        BigInteger f0 = BigInteger.ZERO;
        BigInteger f1 = BigInteger.ONE;
        BigInteger f2 = BigInteger.ONE;

        if (index == 0) return f0;
        if (index == 1) return f1;

        for (BigInteger i = BigInteger.valueOf(3); i.compareTo(
                BigInteger.valueOf(index + 1)) < 0; i = i.add(BigInteger.ONE)) {
            f0 = f1;
            f1 = f2;
            f2 = f0.add(f1);
        }

        return f2;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值