Fibonacci number sequence optimization time complexity

The following is a time complexity of O (n) answers

static int Fbn(int n) {
        int[] a = new int[n];
        a[0] = 1;
        a[1] = 1;
        for (int i = 2; i < n; i++)
        {
            a[i] = a[i - 1] + a[i - 2];
        }
        return a[n - 1]; 
        }

import  java.util.Scanner;
public class Test {
    public static void main(String [] args) {
        Scanner sc=new Scanner(System.in);
        int n = sc.nextInt();
        int [] a = new int[n];

        a [0] = 1;
        a [1] = 1;

        for (int i = 2; i < n; i++) {
            a [i] = a [i-1] + a [i-2];
        }
        System.out.println(a[n-1]);
    }
}
//时间复杂度为O(n)的java写法

** Because the Fibonacci series is not so finally return 0 to n-1 is expressed **

The following is a degree of time complexity O (1) methodHere Insert Picture Description

class Solution { 
public:  
 int Fib(int n) {
 const double s = sqrt(5);      
  return (pow((1+s)/2, n) - pow((1-s)/2, n))/s;
       } 
 }

Another fact should be the solution matrix, but individual capacity is currently limited, temporarily unable Shredded, embarrassing. Ha ha ha.

Published 10 original articles · won praise 8 · views 1169

Guess you like

Origin blog.csdn.net/userIDsss/article/details/105179493