栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

n> 46 Java的斐波那契序列

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

n> 46 Java的斐波那契序列

您可以将其用于将代码转换成BigInteger。

package your.packimport java.math.BigDecimal;import java.math.BigInteger;public class Fibonacci {    private static BigDecimal goldenRatio = new BigDecimal((1 + Math.sqrt(5)) / 2);    private static BigDecimal goldenRatioMin1 = goldenRatio.subtract(BigDecimal.ONE);    private static BigDecimal sqrt5 = new BigDecimal(Math.sqrt(5));    private static BigInteger fib(int n) {        BigInteger nthTerm = new BigInteger("0");        if (n == 2) nthTerm = BigInteger.ONE;        else { BigDecimal minResult = goldenRatio.pow(n).subtract(goldenRatioMin1.pow(n)); nthTerm = minResult.divide(sqrt5,0).toBigInteger(); if (n % 2 == 1 && n < 45){     nthTerm = nthTerm.add(BigInteger.ONE); }        }        return nthTerm;    }    private static int fib2(int n) {        int nthTerm = 0;        if (n == 2) nthTerm = 1;        else { double goldenRatio = (1 + Math.sqrt(5)) / 2; nthTerm = (int) (Math.round(Math.pow(goldenRatio, n)         - Math.pow(1 - goldenRatio, n)) / Math.sqrt(5)); if (n % 2 == 1 && n < 45)     nthTerm++;        }        return nthTerm;    }    public static void main(String []args){        System.out.println(     fib(47)        );    }}

方法fib2是您的代码,fib被转换为BigInteger。干杯



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/455299.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号