1. 程式人生 > >C++_(矩陣)快速冪

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; }