| | 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.NthTribonacciNumber; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class NthTribonacciNumberMatrixExponentiation : INthTribonacciNumber |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(log n) |
| | 19 | | /// Time complexity - O(log n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="n"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public int Tribonacci(int n) |
| 6 | 24 | | { |
| 6 | 25 | | switch (n) |
| | 26 | | { |
| | 27 | | case 0: |
| 1 | 28 | | return 0; |
| | 29 | | case 1: |
| | 30 | | case 2: |
| 2 | 31 | | return 1; |
| | 32 | | } |
| | 33 | |
|
| 3 | 34 | | int[,] matrix = { { 1, 1, 1 }, { 1, 0, 0 }, { 0, 1, 0 } }; |
| | 35 | |
|
| 3 | 36 | | var result = Power(matrix, n - 2); |
| | 37 | |
|
| 3 | 38 | | return result[0, 0] + result[0, 1]; |
| 6 | 39 | | } |
| | 40 | |
|
| | 41 | | private static int[,] Power(int[,] matrix, int power) |
| 3 | 42 | | { |
| 3 | 43 | | int[,] result = { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 } }; |
| | 44 | |
|
| 11 | 45 | | while (power > 0) |
| 8 | 46 | | { |
| 8 | 47 | | if (power % 2 == 1) |
| 6 | 48 | | { |
| 6 | 49 | | result = Multiply(result, matrix); |
| 6 | 50 | | } |
| | 51 | |
|
| 8 | 52 | | matrix = Multiply(matrix, matrix); |
| 8 | 53 | | power /= 2; |
| 8 | 54 | | } |
| | 55 | |
|
| 3 | 56 | | return result; |
| 3 | 57 | | } |
| | 58 | |
|
| | 59 | | private static int[,] Multiply(int[,] a, int[,] b) |
| 14 | 60 | | { |
| 14 | 61 | | var result = new int[3, 3]; |
| | 62 | |
|
| 112 | 63 | | for (var i = 0; i < 3; i++) |
| 42 | 64 | | { |
| 336 | 65 | | for (var j = 0; j < 3; j++) |
| 126 | 66 | | { |
| 126 | 67 | | result[i, j] = 0; |
| | 68 | |
|
| 1008 | 69 | | for (var k = 0; k < 3; k++) |
| 378 | 70 | | { |
| 378 | 71 | | result[i, j] += a[i, k] * b[k, j]; |
| 378 | 72 | | } |
| 126 | 73 | | } |
| 42 | 74 | | } |
| | 75 | |
|
| 14 | 76 | | return result; |
| 14 | 77 | | } |
| | 78 | | } |