#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cassert>

using namespace std;

#define FOR(i,k,n) for(int i=(k); i<(int)n; ++i)
#define REP(i,n) FOR(i,0,n)
#define FORIT(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)

template<class T> void debug(T begin, T end){ for(T i = begin; i != end; ++i) cout<<*i<<" "; cout<<endl; }

typedef long long ll;
const int INF = 100000000;
const double EPS = 1e-8;

int main(){
  while(true){
    int input[10];
    int a[10];
    REP(i, 10) cin>>input[i];
    if(input[0] == -1) break;
    for(int i = 1; i <= 10; i++) a[i - 1] = i;
    int ans = 0;
    do{
      bool ok = true;
      REP(i, 10)if(input[i] != 0 && input[i] != a[i]) ok = false;
      if(!ok) continue;
      int MOD = a[9];
      int v[8][3] = {
        {0,1,2},
        {3,4,5},
        {6,7,8},
        {0,3,6},
        {1,4,7},
        {2,5,8},
        {0,4,8},
        {2,4,6}
      };
      set<int> cnt;
      REP(i, 8){
        int sum = 0;
        REP(j, 3) sum += a[v[i][j]];
        cnt.insert(sum % MOD);
      }
      if(cnt.size() == 1) ans ++;
    }while(next_permutation(a, a + 10));
    cout<<ans<<endl;
  }
  return 0;
}