Cod sursa(job #2945546)

Utilizator Irina.comanIrina Coman Irina.coman Data 23 noiembrie 2022 21:20:40
Problema Al k-lea termen Fibonacci Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <fstream>

using namespace std;

const int M = 666013;
const int N = 2;

void produs(int p[N][N], int a[N][N])
{
    int aux[N][N];
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N; j++)
        {
            aux[i][j] = 0;
            for (int k = 0; k < N; k++)
            {
                aux[i][j] += (long long)p[i][k] * a[k][j] % M;
                aux[i][j] %= M;
            }
        }
    }
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N; j++)
        {
            p[i][j] = aux[i][j];
        }
    }
}

int fibo(int n)
{
    int a[2][2] = { {1, 1}, {1, 0} };
    int p[2][2] = { {1, 0}, {0, 1} };
    n--;
    while (n != 0)
    {
        int cifb = n % 2;
        if (cifb != 0)
        {
            produs(p, a);
        }
        produs(a, a);
        n /= 2;
    }
    return p[0][0];
}

int main()
{
    ifstream in("kfib.in");
    ofstream out("kfib.out");
    int k;
    in >> k;
    out << fibo(k);
    in.close();
    out.close();
    return 0;
}