What is the time complexity of the following for loop method used to compute the nth fibonacci term? [code] int fibo(int n) if n ==

What is the time complexity of the following for loop method used to compute the nth fibonacci term?
Code:
int fibo(int n)
    if n == 0
       return 0 
    else
       prevFib = 0
       curFib = 1
       for i : 1 to n-1
           nextFib = prevFib + curFib
	   prevFib = curFib
           curFib = nextFib
       return curFib
A. O(1)
B. O(n)
C. O(n$^{2}$)
D. Exponential
 
Answer: B
Explanation: To calculate the nth term, the for loop runs (n - 1) times and each time a for loop is run, it takes a constant time. Therefore, the time complexity is of the order of n.
 

Tìm kiếm

Back
Top