Generalized Fibonacci Numbers (original) (raw)

`using System;

class GFG { static void multiply(int[,] F, int[,] M) {

    // Multiply two 2x2 matrices and store result in F
    int x = F[0,0] * M[0,0] + F[0,1] * M[1,0];
    int y = F[0,0] * M[0,1] + F[0,1] * M[1,1];
    int z = F[1,0] * M[0,0] + F[1,1] * M[1,0];
    int w = F[1,0] * M[0,1] + F[1,1] * M[1,1];
    F[0,0] = x; F[0,1] = y;
    F[1,0] = z; F[1,1] = w;
}

static void power(int[,] F, int n, int a, int b) {

    // Raise transformation matrix F to the power n
    int[,] M = { { a, 1 }, { b, 0 } };
    for (int i = 1; i <= n; i++)
        multiply(F, M);
}

static int Fibonacci(int a, int b, int c, int d, int n) {

    // Transformation matrix
    int[,] F = { { a, 1 }, { b, 0 } };

    // Base cases
    if (n == 1)
        return c;
    if (n == 2)
        return d;

    // Initial matrix using base case values
    int[,] initial = { { a * d + b * c, d }, { d, c } };

    // Raise transformation matrix to power n-2
    power(F, n - 2, a, b);

    // Multiply initial matrix with result
    multiply(initial, F);

    // Top left element is the nth term
    return initial[0, 0];
}

static void Main() {
    int a = 1, b = 1, c = 0, d = 1, n = 6;
    Console.WriteLine(Fibonacci(a, b, c, d, n));
}

}

`