| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.FibonacciNumber; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class FibonacciNumberMatrixExponentiation : IFibonacciNumber |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(log n) |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="n"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public int Fib(int n) |
| 5 | 24 | | { |
| 5 | 25 | | if (n <= 1) |
| 2 | 26 | | { |
| 2 | 27 | | return n; |
| | 28 | | } |
| | 29 | |
|
| 3 | 30 | | int[,] f = { { 1, 1 }, { 1, 0 } }; |
| | 31 | |
|
| 3 | 32 | | Power(f, n - 1); |
| | 33 | |
|
| 3 | 34 | | return f[0, 0]; |
| 5 | 35 | | } |
| | 36 | |
|
| | 37 | | private static void Power(int[,] f, int n) |
| 5 | 38 | | { |
| 5 | 39 | | if (n <= 1) |
| 3 | 40 | | { |
| 3 | 41 | | return; |
| | 42 | | } |
| | 43 | |
|
| 2 | 44 | | int[,] m = { { 1, 1 }, { 1, 0 } }; |
| | 45 | |
|
| 2 | 46 | | Power(f, n / 2); |
| 2 | 47 | | Multiply(f, f); |
| | 48 | |
|
| 2 | 49 | | if (n % 2 != 0) |
| 1 | 50 | | { |
| 1 | 51 | | Multiply(f, m); |
| 1 | 52 | | } |
| 5 | 53 | | } |
| | 54 | |
|
| | 55 | | private static void Multiply(int[,] a, int[,] b) |
| 3 | 56 | | { |
| 3 | 57 | | var x = (a[0, 0] * b[0, 0]) + (a[0, 1] * b[1, 0]); |
| 3 | 58 | | var y = (a[0, 0] * b[0, 1]) + (a[0, 1] * b[1, 1]); |
| 3 | 59 | | var z = (a[1, 0] * b[0, 0]) + (a[1, 1] * b[1, 0]); |
| 3 | 60 | | var w = (a[1, 0] * b[0, 1]) + (a[1, 1] * b[1, 1]); |
| | 61 | |
|
| 3 | 62 | | a[0, 0] = x; |
| 3 | 63 | | a[0, 1] = y; |
| 3 | 64 | | a[1, 0] = z; |
| 3 | 65 | | a[1, 1] = w; |
| 3 | 66 | | } |
| | 67 | | } |