- 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;
- }
- }