< Summary

Information
Class: LeetCode.Algorithms.FibonacciNumber.FibonacciNumberMatrixExponentiation
Assembly: LeetCode
File(s): D:\a\LeetCode-CS\LeetCode-CS\source\LeetCode\Algorithms\FibonacciNumber\FibonacciNumberMatrixExponentiation.cs
Line coverage
100%
Covered lines: 30
Uncovered lines: 0
Coverable lines: 30
Total lines: 67
Line coverage: 100%
Branch coverage
100%
Covered branches: 6
Total branches: 6
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
Fib(...)100%22100%
Power(...)100%44100%
Multiply(...)100%11100%

File(s)

D:\a\LeetCode-CS\LeetCode-CS\source\LeetCode\Algorithms\FibonacciNumber\FibonacciNumberMatrixExponentiation.cs

#LineLine coverage
 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
 12namespace LeetCode.Algorithms.FibonacciNumber;
 13
 14/// <inheritdoc />
 15public 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)
 524    {
 525        if (n <= 1)
 226        {
 227            return n;
 28        }
 29
 330        int[,] f = { { 1, 1 }, { 1, 0 } };
 31
 332        Power(f, n - 1);
 33
 334        return f[0, 0];
 535    }
 36
 37    private static void Power(int[,] f, int n)
 538    {
 539        if (n <= 1)
 340        {
 341            return;
 42        }
 43
 244        int[,] m = { { 1, 1 }, { 1, 0 } };
 45
 246        Power(f, n / 2);
 247        Multiply(f, f);
 48
 249        if (n % 2 != 0)
 150        {
 151            Multiply(f, m);
 152        }
 553    }
 54
 55    private static void Multiply(int[,] a, int[,] b)
 356    {
 357        var x = (a[0, 0] * b[0, 0]) + (a[0, 1] * b[1, 0]);
 358        var y = (a[0, 0] * b[0, 1]) + (a[0, 1] * b[1, 1]);
 359        var z = (a[1, 0] * b[0, 0]) + (a[1, 1] * b[1, 0]);
 360        var w = (a[1, 0] * b[0, 1]) + (a[1, 1] * b[1, 1]);
 61
 362        a[0, 0] = x;
 363        a[0, 1] = y;
 364        a[1, 0] = z;
 365        a[1, 1] = w;
 366    }
 67}