Cod sursa(job #3294734)

Utilizator Dragos_MatuDragos Gabriel Matu Dragos_Matu Data 27 aprilie 2025 19:04:09
Problema Al k-lea termen Fibonacci Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.09 kb
#include <iostream>
#include <fstream>
#include <stdlib.h>
#define MOD 666013
using namespace std;

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

void sq_matrix_multiply(unsigned long stMatrix[2][2], unsigned long ndMatrix[2][2], unsigned long result[2][2])
{
    result[0][0] = (stMatrix[0][0] * ndMatrix[0][0] + stMatrix[0][1] * ndMatrix[1][0]) % MOD;
    result[0][1] = (stMatrix[0][0] * ndMatrix[0][1] + stMatrix[0][1] * ndMatrix[1][1]) % MOD;
    result[1][0] = (stMatrix[1][0] * ndMatrix[0][0] + stMatrix[1][1] * ndMatrix[1][0]) % MOD;
    result[1][1] = (stMatrix[1][0] * ndMatrix[0][1] + stMatrix[1][1] * ndMatrix[1][1]) % MOD;
}

void fast_pow(unsigned long matrix[2][2], unsigned long long power, unsigned long final_result[2][2])
{
    unsigned long result[2][2] = {{1, 0}, {0, 1}};
    unsigned long temp[2][2] = {{0, 0}, {0, 0}};
    if (power == -1)
    {
        power = 0;
    }
    while (power > 0)
    {
        if (power % 2 == 1)
        {
            sq_matrix_multiply(result, matrix, temp);
            for (int i = 0; i < 2; i++)
            {
                for (int j = 0; j < 2; j++)
                {
                    result[i][j] = temp[i][j];
                }
            }
        }
        sq_matrix_multiply(matrix, matrix, temp);
        for (int i = 0; i < 2; i++)
        {
            for (int j = 0; j < 2; j++)
            {
                matrix[i][j] = temp[i][j];
            }
        }
        power = power / 2;
    }
    for (int i = 0; i < 2; i++)
    {
        for (int j = 0; j < 2; j++)
        {
            final_result[i][j] = result[i][j];
        }
    }
}

int main()
{
    unsigned long matrix[2][2], result[2][2] = {0};
    matrix[0][0] = 0;
    matrix[0][1] = 1;
    matrix[1][0] = 1;
    matrix[1][1] = 1;
    long long power;
    cin >> power;
    power -= 2;
    fast_pow(matrix, power, result);
    cout << result[0][0] << " " << result[0][1] << "\n"
         << result[1][0] << " " << result[1][1] << "\n";
    cout << result[0][1] + result[1][1];
    fout << result[0][1] + result[1][1];
}