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

Function fib_matrix_np

maths/fibonacci.py:282–317  ·  view source on GitHub ↗

Calculates the n-th Fibonacci number using matrix exponentiation. https://www.nayuki.io/page/fast-fibonacci-algorithms#:~:text= Summary:%20The%20two%20fast%20Fibonacci%20algorithms%20are%20matrix Args: n: Fibonacci sequence index Returns: The n-th Fibonacci num

(n: int)

Source from the content-addressed store, hash-verified

280
281
282def fib_matrix_np(n: int) -> int:
283 """
284 Calculates the n-th Fibonacci number using matrix exponentiation.
285 https://www.nayuki.io/page/fast-fibonacci-algorithms#:~:text=
286 Summary:%20The%20two%20fast%20Fibonacci%20algorithms%20are%20matrix
287
288 Args:
289 n: Fibonacci sequence index
290
291 Returns:
292 The n-th Fibonacci number.
293
294 Raises:
295 ValueError: If n is negative.
296
297 >>> fib_matrix_np(0)
298 0
299 >>> fib_matrix_np(1)
300 1
301 >>> fib_matrix_np(5)
302 5
303 >>> fib_matrix_np(10)
304 55
305 >>> fib_matrix_np(-1)
306 Traceback (most recent call last):
307 ...
308 ValueError: n is negative
309 """
310 if n < 0:
311 raise ValueError("n is negative")
312 if n == 0:
313 return 0
314
315 m = np.array([[1, 1], [1, 0]], dtype=int)
316 result = matrix_pow_np(m, n - 1)
317 return int(result[0, 0])
318
319
320if __name__ == "__main__":

Callers

nothing calls this directly

Calls 1

matrix_pow_npFunction · 0.85

Tested by

no test coverage detected