n_fibonacci

py

School

Brigham Young University, Idaho *

*We aren’t endorsed by this school

Course

160

Subject

Computer Science

Date

Nov 24, 2024

Type

py

Pages

1

Uploaded by PrivateStarPartridge3

Report
import time #Brute Force Solution Time: O(2^n) . Space: O(1) def getNthFib(n): if n == 1: return 0 elif n == 2: return 1 else: return getNthFib(n - 1) + getNthFib(n - 2) n = 5 start_time1 = time.time() print("Value at position", n, " = ", getNthFib(n)) first = time.time() - start_time1 print("--- %s seconds ---" % (first)) #Optimal Solution def getNthFib2(n, helper = {1:0, 2:1}): if n == 1: return helper[1] elif n == 2: return helper[2] else: helper[n] = getNthFib2(n - 1,) + getNthFib2(n - 2) return helper[n] n = 5 start_time2 = time.time() print("Value at position", n, " = ", getNthFib2(n)) second = time.time() - start_time2 print("--- %s seconds ---" % (second)) if first > second: print("getNthFib2 is faster than getNthFib1") else: print("getNthFib1 is faster than getNthFib2") """OutPut: Value at position 5 = 3 --- 2.002716064453125e-05 seconds --- Value at position 5 = 3 --- 5.0067901611328125e-06 seconds --- getNthFib2 is faster than getNthFib1"""
Discover more documents: Sign up today!
Unlock a world of knowledge! Explore tailored content for a richer learning experience. Here's what you'll get:
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help