luogu1306 斐波那契公约数

作者:

在

,

$$ \text{设斐波那契数列的第}n\text{项的值为}a\text{,第}n+\text{1项的值为}b \\ \text{则}f\left( n+1 \right) =b,f\left( n+2 \right) =a+b,f\left( n+3 \right) =a+2b \\ f\left( m \right) =f\left( m-n-1 \right) a+f\left( m-n \right) b \\ gcd\left( f\left( n \right) ,f\left( m \right) \right) =gcd\left( f\left( n \right) ,f\left( m \right) \%f\left( n \right) \right) =gcd\left( a,f\left( m-n \right) b \right) \\ a,b\text{互质,所以} \\ gcd\left( f\left( n \right) ,f\left( m \right) \right) =gcd\left( f\left( n \right) ,f\left( m-n \right) \right) \\ \text{可以递归证明} \\ gcd\left( f\left( n \right) ,f\left( m \right) \right) =gcd\left( f\left( n \right) ,f\left( m\%n \right) \right) =gcd\left( f\left( gcd\left( n,m \right) \right) ,f\left( 0 \right) \right) =f\left( gcd\left( n,m \right) \right) $$

#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
using std::cin;
using std::cout;
using std::endl;

using int_t = long long int;

const int_t mod = 1e8;

struct Matrix
{
    int_t data[21][21];
    int_t n;
    Matrix(int_t n)
    {
        this->n = n;
        memset(data, 0, sizeof(data));
    }
    int_t &operator()(int_t r, int_t c)
    {
        return data[r][c];
    }
    int_t *operator[](int_t row)
    {
        return data[row];
    }
    Matrix operator*(Matrix another)
    {
        Matrix result(n);
        for (int_t i = 1; i <= n; i++)
        {
            for (int_t j = 1; j <= n; j++)
            {
                for (int_t k = 1; k <= n; k++)
                {
                    result[i][j] = (result[i][j] + (*this)[i][k] * another[k][j] % mod) % mod;
                }
            }
        }
        return result;
    }
    Matrix operator^(int_t index)
    {
        Matrix base = *this;
        Matrix result(n);
        for (int_t i = 1; i <= n; i++)
            result[i][i] = 1;
        while (index)
        {
            if (index & 1)
                result = result * base;
            base = base * base;
            index >>= 1;
        }
        return result;
    }
};
int_t gcd(int_t a, int_t b)
{
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
int main()
{
    int_t a, b;
    cin >> a >> b;
    int_t n = gcd(a, b);

    Matrix init(2);
    init(1, 2) = 1;
    Matrix trans(2);
    trans(2, 2) = 1;
    trans(1, 2) = 1;
    trans(2, 1) = 1;
    char buff[20];
    sprintf(buff, "%lld", (init * (trans ^ n))[1][1]);
    std::string str = buff;
    // while (str.length() < 8)
    //     str = '0' + str;
    cout << str << endl;

    return 0;
}

 

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理。