#include <iostream>
#include <algorithm>
using namespace std;
const int W = 3;
const int H = 3;
const int N = 10;
int A[N];

bool isValid(int B[]) {
  for(int i = 0; i < N; ++i) {
    if(A[i] != 0 && A[i] != B[i]) return false;
  }
  return true;
}

int sumLine(int B[], int x, int y, int dx, int dy) {
  int res = 0;
  for(;x >= 0 && x < W && y >= 0 && y < H; x += dx, y += dy) {
    res += B[x+y*W];
  }
  return res;
}

bool count(int B[]) {
  const int mod = B[N-1];
  const int m = sumLine(B,0,0,1,1) % mod;
  if(m != sumLine(B,0,2,1,-1) % mod) return false;
  for(int i = 0; i < 3; ++i)
    if(m != sumLine(B,0,i,1,0) % mod) return false;
  for(int i = 0; i < 3; ++i)
    if(m != sumLine(B,i,0,0,1) % mod) return false;
  return true;
}

int main() {
  while(1) {
    {
      bool flag = false;
      for(int i = 0; i < N; ++i) {
        cin >> A[i];
        if(A[i] != -1) flag = true;
      }
      if(!flag) break;
    }
    int B[N];
    for(int i = 0; i < N; ++i) B[i] = i+1;
    int res = 0;
    do {
      if(!isValid(B)) continue;
      res += count(B);
    } while(next_permutation(B, B+N));
    cout << res << endl;
  }
  return 0;
}