Cod sursa(job #3272147)

Utilizator solicasolica solica solica Data 28 ianuarie 2025 16:28:30
Problema Al k-lea termen Fibonacci Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.95 kb
/*
  ____   ___  _     ___ ____    _
 / ___| / _ \| |   |_ _/ ___|  / \
 \___ \| | | | |    | | |     / _ \
  ___) | |_| | |___ | | |___ / ___ \
 |____/ \___/|_____|___\____/_/   \_\

*/
#include <bits/stdc++.h>

using namespace std;

#define pb push_back
#define int long long int
#define pii pair<int,int>

const int NMAX = 2e5+9;

const int MOD = 666013;

int binpow(int n, int k)
{
    if (k==0)
    {
        return 1;
    }
    int x=binpow(n,k/2)%MOD;
    if (k%2==0)
    {
        return x*x%MOD;
    }
    else
    {
        return x*x%MOD*n%MOD;
    }
}

ifstream fin ("kfib.in");
ofstream fout ("kfib.out");

#define cin fin
#define cout fout

int n;

struct matrix
{
    int mat[3][3];
    int n,m;
};

void produs (matrix a, matrix b, matrix &c)
{
    c.n=a.n,c.m=b.m;
    for (int i=1; i<=c.n; i++)
    {
        for (int j=1; j<=c.m; j++)
        {
            c.mat[i][j]=0;
            for (int k=1; k<=a.m; k++)
            {
                c.mat[i][j]+=a.mat[i][k]*b.mat[k][j];
                c.mat[i][j]%=MOD;
            }
        }
    }
}

matrix exp_rapida (matrix a, int n)
{
    if (n==1)
    {
        return a;  
    }
    if (n%2==0)
    {
        matrix z,rz=exp_rapida (a,n/2);
        produs(rz,rz,z);
        return z;
    }
    else
    {
        matrix z,prd,rz;
        prd=exp_rapida(a,n/2);
        produs(prd,prd,z);
        produs(z,a,rz);
        return rz;
    }
}

void run_case ()
{
    cin>>n;
    matrix fibo,init;
    init.n=1,init.m=2;
    init.mat[1][1]=0,init.mat[1][2]=1;
    fibo.n=fibo.m=2;
    fibo.mat[1][1]=0;
    fibo.mat[1][2]=fibo.mat[2][1]=fibo.mat[2][2]=1;
    matrix rez;
    produs(init,exp_rapida (fibo,n-1),rez);
    cout<<rez.mat[1][2]<<'\n';
}

signed main ()
{
    ios_base::sync_with_stdio(0);
    cin.tie(NULL),cout.tie ();
    int teste;
    teste=1;
    while (teste--)
    {
        run_case();
    }
}