gpt4 book ai didi

java - 使用 'fib(N) = [Phi^N – phi^N]/Sqrt[5]' 公式计算 Fibonacci 项的时间复杂度是多少?

转载 作者:行者123 更新时间:2023-12-05 08:03:37 27 4
gpt4 key购买 nike

<分区>

Fibonacci 的正常递归是 Fib(N)= Fib(N-1)+Fib(n-2),其时间复杂度为 2^N。为了降低时间复杂度,我们有以下公式:

Fib(N) = [Phi^N – phi^N]/Sqrt[5] Source

其中 Phi= (1 + Sqrt[5])/2phi = (1-Sqrt[5])/2;phi=Phi-1 Source

我的java代码如下:

import java.util.*;
import java.lang.*;
public class Main
{
public static void main(String[] args) {
System.out.println(fib(50)+"");
}

static long fib(int N){
final double sqrtFive=Math.sqrt(5);
double Phi=(sqrtFive+1)/2;
double phi=Phi-1;
double fibN=(Math.pow(Phi,N)-Math.pow(phi,N))/sqrtFive;
return (long) fibN;
}
}

我的代码的时间复杂度是多少?

O(1)? because modern computer are superfast in computation soMath.pow(base,power) will be almost constant for any power.

O(logn+logn) means O(logn)? because I'm doingMath.pow(Phi,N)-Math.pow(phi,N) and Math.pow() function takes logN time.

我很困惑,请帮帮我。

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com