import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

int[] xs;

bool input() {
    xs = readln.chomp.split(" ").map!(to!int).array;
    return xs[0] != -1;
}

void solve() {
    auto used = new bool[11];
    foreach (x; xs) {
        if (x == 0) continue;
        used[ x - 1 ] = true;
    }
    auto F = xs.dup;

    bool check() {
        //writeln(F);
        int M = F[9];
        int s = F[0 .. 3].reduce!"a + b" % M;
        auto dirs = [ [ 0, 1, 2 ],
                      [ 3, 4, 5 ],
                      [ 6, 7, 8 ],
                      [ 0, 4, 8 ],
                      [ 2, 4, 6 ],
                      [ 0, 3, 6 ],
                      [ 1, 4, 7 ],
                      [ 2, 5, 8 ] ];
        foreach (dir; dirs) {
            int sum = 0;
            foreach (index; dir) {
                sum += F[index];
            }
            if (sum % M != s) return false;
        }
        return true;
    }

    int ans = 0;
    void dfs(int index) {
        if (index == 10) {
            ans += check();
            return;
        }
        if (F[index] == 0) {
            foreach (int i; 0 .. 10) {
                if (used[i]) continue;
                used[i] = true;
                F[index] = i + 1;
                dfs(index + 1);
                F[index] = 0;
                used[i] = false;
            }
        } else {
            dfs(index + 1);
        }
    }
    dfs(0);
    writeln(ans);
}

void main() {
    while (input) solve;
}