------ matrix multiplication Allison Fibonacci

Allison mathematics, especially for the number of columns is very interested. Once you've reviewed the Fibonacci sequence, he created many strange series. For example S (n) S (n)

Nn represents the Fibonacci ago

Items and modmmodm

Value, i.e., S (n) = (F1 + F2 + ... + Fn) modmS (n) = (F1 + F2 + ... + Fn) modm

, 其中 F1 = F2 = 1, Fi = Fi-1 + Fi-2F1 = F2 = 1, Fi = Fi-1 + Fi-2

. But it is still a piece of cake for Allison. Finally, she found a problem they can not solve. With T (n) = (F1 + 2F2 + 3F3 + ... + nFn) modmT (n) = (F1 + 2F2 + 3F3 + ... + nFn) modm

A front Fibonacci sequence nn

After the entry deformation and modmmodm

Value. Allison now tell you a nn

And mm

Request the T (n) T (n)

Value. SCHEME input line, comprising two integers nn

And mm

. SCHEME output line, the output T (n) T (n)

Value. Data range 1≤n, m≤231-11≤n, m≤231-1

Sample input: 55
Output Sample: 1
Sample construed T (5) = (1 + 2 × 1 + 3 × 2 + 4 × 3 + 5 × 5) mod5 = 1

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long LL;
const int N = 4;
int n, m;
void mul(int c[][N], int a[][N], int b[][N]){
 static int t[N][N];
 memset(t, 0, sizeof t);
 for (int i = 0; i < N; i ++)
   for (int j = 0; j < N; j ++)
      for (int k = 0; k < N; k ++)
        t[i][j] = (t[i][j] + (LL)a[i][k] * b[k][j]) % m;
 memcpy(c, t, sizeof t);
}
int main(){
 cin >> n >> m;
 int f1[N][N] = {1, 1, 1, 0};
 int a[N][N] = {
   {0, 1, 0, 0},
        {1, 1, 1, 0},
        {0, 0, 1, 1},
        {0, 0, 0, 1},
 };
 int k = n - 1;
 while(k){
  if (k & 1)   mul(f1, f1, a);
  mul(a, a, a);
  k >>= 1;
 }
  cout << (((LL)n * f1[0][2] - f1[0][3]) % m + m) % m << endl;
 return 0;
}
Published 106 original articles · won praise 67 · views 5413

Guess you like

Origin blog.csdn.net/qq_45772483/article/details/105032291