// C# program to count number of
// ways to reach nth stair.
using System;
class GfG {
// Function to multiply two 3x3 matrices
static void multiply(int[,] a, int[,] b) {
// Matrix to store the result
int[,] c = new int[3, 3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 3; k++) {
c[i, j] += a[i, k] * b[k, j];
}
}
}
// Copy the result back to the first matrix
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
a[i, j] = c[i, j];
}
}
}
// Function to calculate (Matrix M) ^ expo
static int[,] power(int[,] m, int expo) {
// Initialize result with identity matrix
int[,] ans = { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 } };
// Fast Exponentiation
while (expo != 0) {
if ((expo & 1) != 0)
multiply(ans, m);
multiply(m, m);
expo >>= 1;
}
return ans;
}
// function to count number of
// ways to reach nth stair.
static int countWays(int n) {
// base condition
if (n == 0 || n == 1)
return 1;
// Matrix M to generate the next step value.
int[,] m = { { 1, 1, 1 }, { 1, 0, 0 }, { 0, 1, 0 } };
// first 3 values of steps are:
// findWays(0) = 1
// findWays(1) = 1
// findWays(2) = 2
// f = {{findWays(2), 0, 0}, {findWays(1), 0, 0},
// {findWays(0), 0,0}}
int[,] f = { { 2, 0, 0 }, { 1, 0, 0 }, { 1, 0, 0 } };
int[,] res = power(m, n - 2);
multiply(res, f);
return res[0, 0];
}
static void Main(string[] args) {
int n = 4;
Console.WriteLine(countWays(n));
}
}