• Java、GCD的执行时间


    1. package algorithm;
    2. import java.math.BigInteger;
    3. /**
    4. * @author: xyz
    5. * @create: 2022/8/12
    6. * @Description:
    7. * @FileName: Exercise22_06
    8. * @History:
    9. * @自定义内容:
    10. */
    11. public class Exercise22_06 {
    12. public static void main(String[] args) {
    13. BigInteger[] fab = new BigInteger[5];
    14. for (int i = 41, j = 0; i <= 45; i++, j++) //获取斐波那契数
    15. fab[j] = fab(i);
    16. long startTime = System.currentTimeMillis();
    17. System.out.println("\t\t\t\t\t\40\t\t41\t\t42\t\t43\t\t44\t\t45");
    18. System.out.print("程序清单22.3GCD\t\t\t\t\t");
    19. for (int i = 0; i < fab.length - 1; i++)
    20. System.out.print(gcd22_3(fab[i], fab[i + 1]) + "\t\t");
    21. long endTime = System.currentTimeMillis();
    22. long executionTime = endTime - startTime;
    23. System.out.println("\t执行时间:" + executionTime);
    24. startTime = System.currentTimeMillis();
    25. System.out.print("程序清单22.4GCDEuclid\t\t\t");
    26. for (int i = 0; i < fab.length - 1; i++)
    27. System.out.print(gcd22_4(fab[i], fab[i + 1]) + "\t\t");
    28. endTime = System.currentTimeMillis();
    29. executionTime = endTime - startTime;
    30. System.out.println("\t执行时间:" + executionTime);
    31. }
    32. /** 程序清单22.3GCD */
    33. public static BigInteger gcd22_3(BigInteger m, BigInteger n) {
    34. BigInteger gcd = BigInteger.ONE;
    35. //m % n == 0,返回n
    36. if (m.mod(n).equals(BigInteger.ZERO)) return n;
    37. //从n / 2开始,查找第一个能被m和n同时整除的数k
    38. for (BigInteger k = n.divide(BigInteger.valueOf(2)); k.compareTo(
    39. BigInteger.ZERO) > 0; k = k.subtract(BigInteger.ONE)) {
    40. if (m.mod(k).equals(BigInteger.ZERO) && n.mod(k).equals(BigInteger.ZERO)) {
    41. gcd = k;
    42. break;
    43. }
    44. }
    45. return gcd;
    46. }
    47. /** 程序清单22.4GCDEuclid */
    48. public static BigInteger gcd22_4(BigInteger m, BigInteger n) {
    49. return m.mod(n).equals(BigInteger.ZERO) ? n : gcd22_4(n, m.mod(n));
    50. }
    51. /** 返回斐波那契数 */
    52. public static BigInteger fab(long index) {
    53. BigInteger f0 = BigInteger.ZERO;
    54. BigInteger f1 = BigInteger.ONE;
    55. BigInteger f2 = BigInteger.ONE;
    56. if (index == 0) return f0;
    57. if (index == 1) return f1;
    58. for (BigInteger i = BigInteger.valueOf(3); i.compareTo(
    59. BigInteger.valueOf(index + 1)) < 0; i = i.add(BigInteger.ONE)) {
    60. f0 = f1;
    61. f1 = f2;
    62. f2 = f0.add(f1);
    63. }
    64. return f2;
    65. }
    66. }

     

  • 相关阅读:
    S7-1200/1500程序设计规范指南之一:导言
    Linux系统编程学习笔记
    volatile关键字详解
    .bat批处理命令处理文件
    Synchronized锁详解
    【目标跟踪】|数据集汇总
    以软硬协同最佳实践构建智能算力,燧原科技WAIC大会上发布云燧智算机
    大数据在电力行业的应用案例100讲(十三)-可视化在线建模
    Java计算机毕业设计体育城场地预定系统后台源码+系统+数据库+lw文档
    Nginx - 本机读取服务器图像、视频
  • 原文地址:https://blog.csdn.net/m0_62659797/article/details/126321367