MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / fib

Function fib

maths/primelib.py:800–835  ·  view source on GitHub ↗

input: positive integer 'n' returns the n-th fibonacci term , indexing by 0 >>> fib(0) 1 >>> fib(5) 8 >>> fib(20) 10946 >>> fib(99) 354224848179261915075 >>> fib(-1) Traceback (most recent call last): ... AssertionError: 'n' must been an int

(n: int)

Source from the content-addressed store, hash-verified

798
799
800def fib(n: int) -> int:
801 """
802 input: positive integer 'n'
803 returns the n-th fibonacci term , indexing by 0
804
805 >>> fib(0)
806 1
807 >>> fib(5)
808 8
809 >>> fib(20)
810 10946
811 >>> fib(99)
812 354224848179261915075
813 >>> fib(-1)
814 Traceback (most recent call last):
815 ...
816 AssertionError: 'n' must been an int and >= 0
817 >>> fib("test")
818 Traceback (most recent call last):
819 ...
820 AssertionError: 'n' must been an int and >= 0
821 """
822
823 # precondition
824 assert isinstance(n, int) and (n >= 0), "'n' must been an int and >= 0"
825
826 tmp = 0
827 fib1 = 1
828 ans = 1 # this will be return
829
830 for _ in range(n - 1):
831 tmp = ans
832 ans += fib1
833 fib1 = tmp
834
835 return ans
836
837
838if __name__ == "__main__":

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected