What is this program failing in?

I use a divide an conquer aproach to solve the followoing problem:

Given a 2x2 matrix of integers M, and two integers n and m, compute (M^n)%m.

The automatic judge tells me its wrong but I really cant see where the mistake is.

Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
  
#include <iostream>
#include <vector>
using namespace std;

void prod_mat(vector< vector<int> >& M1, vector < vector<int> >& M2, vector < vector<int> >& RES, int m) {
     for (int j = 0; j < 2; ++j) {
		for (int k = 0; k < 2; ++k) {
			for (int i = 0; i < 2; ++i) {
				RES[i][j] += M1[i][k]*M2[k][j];
			}
		}
	}     
}

vector< vector<int> > matn_modk(vector< vector<int> > M, int n, int m) {
     vector< vector<int> > R(2, vector<int>(2));
     if (n == 1) return M;      
     else {
         for (int i = 0; i < 2; ++i) {
             for (int j = 0; j < 2; ++j) { 
                M[i][j] = M[i][j]%m;     
             }
         }                
         
         vector< vector<int> > AUX(2, vector<int>(2));
         AUX = matn_modk(M, n/2, m);
         
         vector< vector<int> > RES(2, vector<int>(2, 0) ); 
         prod_mat(AUX, AUX, RES, m);
          
         vector< vector<int> > AUX2(2, vector<int>(2));    
         if (n%2 == 1) {
             prod_mat(RES, M, AUX2, m);
             for (int i = 0; i < 2; ++i) 
                 for (int j = 0; j < 2; ++j) 
                     RES[i][j] = AUX2[i][j]%m; 
         }
         for (int i = 0; i < 2; ++i) 
             for (int j = 0; j < 2; ++j) 
                 R[i][j] = RES[i][j]%m;        
     } 
     return R;
}

int main () {
    vector< vector<int> > M(2, vector<int>(2) ); 
    vector< vector<int> > R(2, vector<int>(2) ); 
    while(cin >> M[0][0]) {
   		cin >> M[0][1] >> M[1][0] >> M[1][1];
        
    int n, m; cin >> n >> m;
    if (n == 0) {
       cout << "1 0" << endl << "0 1" << endl;
    }
    else { R = matn_modk(M, n, m);
        for (int i = 0; i < 2; ++i) {
         for (int j = 0; j < 2; ++j) { 
             if (j == 1) cout << " ";
             cout << R[i][j]; 
         }
         cout << endl;
    }
}   
 cout << "----------" << endl;        
    }
}


Thanks a lot and sorry if the code is unordered, style recommendations are apreciated and welcome
Topic archived. No new replies allowed.