知行合一

BUILD YOUR WORLD

C++_(矩阵)快速幂

这里写图片描述

#include <iostream>
#include <cstdio>

using namespace std;
const int MOD = 1000;

int POW(long long &num);
int times;
long long N;

int main()
{
    scanf("%d", &times);
    while(times--)
    {
        scanf("%lld", &N);
        printf("%d\n", POW(N));
    }
    return 0;
}


int POW(long long &num)
{
    int ans = 1;
    long long t = num;
    while(t)
    {
        if(t&1)
        {
            ans = (ans*num)%MOD;
        }
        num = num*num%MOD;
        t = t>>1;
    }
    return ans%10;
}

这里写图片描述

一开始一个个相乘超时了最后发现可以用上面那个算法,A了

#include <iostream>
#include <cstdio>
#define MOD 10000

using namespace std;

struct Matrix
{
    int lt, rt, lb, rb;
    Matrix() : lt(1), rt(1), lb(1), rb(0){}
    Matrix& operator*(const Matrix m)
    {
        Matrix temp = (*this);
        lt = (temp.lt*m.lt)%MOD + (temp.rt*m.lb)%MOD;
        rt = (temp.lt*m.rt)%MOD + (temp.rt*m.rb)%MOD;
        lb = (temp.lb*m.lt)%MOD + (temp.rb*m.lb)%MOD;
        rb = (temp.lb*m.rt)%MOD + (temp.rb*m.rb)%MOD;
        return (*this);
    }
};

long long n;

int getAns();

int main()
{
    while(~scanf("%lld", &n))
    {
        if(n == -1) break;
        if(n == 0)
        {
            printf("0\n");
            continue;
        }

        printf("%d\n", getAns());

    }
    return 0;
}


int getAns()
{
    Matrix m;
    n--;
    //long long t = n;
    Matrix res;
    Matrix temp;
    while(n)
    {
        if(n&1)
        {
            m= m * res;
            //cout << m.lt << " " << m.rt << endl << m.lb << " " << m.rb << endl;
        }
        res = res * res;
        //cout << res.lt << " " << res.rt << endl << res.lb << " " << res.rb << endl;
        n = n>>1;
    }



    return (m.rt)%MOD;
}
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a7055117a/article/details/51407846
个人分类: 计算机算法 C++
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭