import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskD solver = new TaskD();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskD {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            long n = in.nextLong();
            int m = in.nextInt();
            int[] number = new int[Long.toString(n).length()];
            int[] freq = new int[10];
            long[] fact = new long[18];
            fact[0] = 1;
            for (int i = 1; i < fact.length; i++)
                fact[i] = fact[i - 1] * i;
            int numberLength = 0;
            for (char c : Long.toString(n).toCharArray()) {
                freq[c - '0']++;
                number[numberLength++] = c - '0';
            }

            long[][] dp = new long[1 << numberLength][m];
            dp[0][0] = 1;
            for (int mask = 0; mask < (1 << numberLength); mask++) {
                for (int rem = 0; rem < m; rem++) {
                    for (int di = 0; di < numberLength; di++) {
                        if (mask == 0 && number[di] == 0)
                            continue;

                        if ((mask & (1 << di)) != 0)
                            continue;

                        dp[mask | (1 << di)][(rem * 10 + number[di]) % m] += dp[mask][rem];
                    }
                }
            }

            long ans = dp[(1 << numberLength) - 1][0];
            for (int i = 0; i < freq.length; i++) {
                ans /= fact[freq[i]];
            }
            out.println(ans);
        }

    }

    static class InputReader {
        final InputStream is;
        final byte[] buffer = new byte[1024];
        int curCharIdx;
        int nChars;

        public InputReader(InputStream is) {
            this.is = is;
        }

        public int read() {
            if (curCharIdx >= nChars) {
                try {
                    curCharIdx = 0;
                    nChars = is.read(buffer);
                    if (nChars == -1)
                        return -1;
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return buffer[curCharIdx++];
        }

        public int nextInt() {
            int sign = 1;
            int c = skipDelims();
            if (c == '-') {
                sign = -1;
                c = read();
                if (isDelim(c))
                    throw new RuntimeException("Incorrect format");
            }
            int val = 0;
            while (c != -1 && !isDelim(c)) {
                if (!isDigit(c))
                    throw new RuntimeException("Incorrect format");
                val = 10 * val + (c - '0');
                c = read();
            }
            return val * sign;
        }

        public long nextLong() {
            int sign = 1;
            int c = skipDelims();
            if (c == '-') {
                sign = -1;
                c = read();
                if (isDelim(c))
                    throw new RuntimeException("Incorrect format");
            }
            long val = 0;
            while (c != -1 && !isDelim(c)) {
                if (!isDigit(c))
                    throw new RuntimeException("Incorrect format");
                val = 10L * val + (c - '0');
                c = read();
            }
            return val * sign;
        }

        private final int skipDelims() {
            int c = read();
            while (isDelim(c)) {
                c = read();
            }
            return c;
        }

        private static boolean isDelim(final int c) {
            return c == ' ' ||
                    c == '\n' ||
                    c == '\t' ||
                    c == '\r' ||
                    c == '\f';
        }

        private static boolean isDigit(final int c) {
            return '0' <= c && c <= '9';
        }

    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Collections;
import java.io.InputStream;
import java.util.ArrayList;
/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Alex
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        TaskD solver = new TaskD();
        solver.solve(1, in, out);
        out.close();
    }
    static class TaskD {
        int[] a;
        int m;
        long[][] mem;
        int[] powers10;
        long DONE;
        long[] dp(int used) {
            if (mem[used] != null) return mem[used];
            if (used == DONE) {
                long[] res = new long[m];
                res[0] = 1;
                return res;
            }
            int index = Integer.bitCount(used);
            long[] res = new long[m];
            for (int pos = 0; pos < a.length; pos++) {
                if (index == 0 && a[pos] == 0) continue;
                if (((used >> pos) & 1) != 0) continue;
                long[] get = dp(used | (1 << pos));
                int curval = powers10[a.length - index - 1];
                for (int mod = 0; mod < get.length; mod++) {
                    res[(curval * a[pos] + mod) % m] += get[mod];
                }
            }
            return mem[used] = res;
        }
        public void solve(int testNumber, InputReader in, OutputWriter out) {
            long n = in.readLong();
            m = in.readInt();
            a = toArray(n);
            Arrays.sort(a);
            DONE = (1 << a.length) - 1;
            powers10 = new int[a.length];
            powers10[0] = 1 % m;
            for (int i = 1; i < powers10.length; i++) {
                powers10[i] = powers10[i - 1] * 10;
                powers10[i] %= m;
            }
            mem = new long[1 << a.length][];
            long[] res = dp(0);
            long divisor = 1;
            int[] count = new int[10];
            for (int val : a) count[val]++;
            for (int c : count) divisor *= IntegerUtils.factorial(c);
            out.printLine(res[0] / divisor);
        }
        private int[] toArray(long n) {
            ArrayList<Integer> al = new ArrayList<>();
            while (n > 0) {
                int last = (int) (n % 10);
                al.add(last);
                n /= 10;
            }
            Collections.reverse(al);
            int[] res = new int[al.size()];
            for (int i = 0; i < res.length; i++) res[i] = al.get(i);
            return res;
        }
    }
    static class OutputWriter {
        private final PrintWriter writer;
        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }
        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }
        public void close() {
            writer.close();
        }
        public void printLine(long i) {
            writer.println(i);
        }
    }
    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;
        public InputReader(InputStream stream) {
            this.stream = stream;
        }
        public int read() {
            if (numChars == -1)
                throw new InputMismatchException();
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }
        public int readInt() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }
        public long readLong() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }
        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return isWhitespace(c);
        }
        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }
        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
    }
    static class IntegerUtils {
        public static long factorial(int n) {
            long result = 1;
            for (int i = 2; i <= n; i++)
                result *= i;
            return result;
        }
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Alex
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        TaskD solver = new TaskD();
        solver.solve(1, in, out);
        out.close();
    }
    static class TaskD {
        int[] a;
        int m;
        long[][] mem;
        int[] powers10;
        long DONE;
        long[] dp(int used) {
            if (mem[used] != null) return mem[used];
            if (used == DONE) {
                long[] res = new long[m];
                res[0] = 1;
                return res;
            }
            int index = Integer.bitCount(used);
            long[] res = new long[m];
            for (int pos = 0; pos < a.length; pos++) {
                if (index == 0 && a[pos] == 0) continue;
                if (((used >> pos) & 1) != 0) continue;
                long[] get = dp(used | (1 << pos));
                int curval = powers10[a.length - index - 1];
                for (int mod = 0; mod < get.length; mod++) {
                    res[(curval * a[pos] + mod) % m] += get[mod];
                }
            }
            return mem[used] = res;
        }
        public void solve(int testNumber, InputReader in, OutputWriter out) {
            char[] input = in.next().toCharArray();
            a = new int[input.length];
            for (int i = 0; i < a.length; i++) a[i] = (input[i] - '0');
            Arrays.sort(a);
            m = in.readInt();
            DONE = (1 << a.length) - 1;
            powers10 = new int[a.length];
            powers10[0] = 1 % m;
            for (int i = 1; i < powers10.length; i++) {
                powers10[i] = powers10[i - 1] * 10;
                powers10[i] %= m;
            }
            mem = new long[1 << a.length][];
            long[] res = dp(0);
            long divisor = 1;
            int[] count = new int[10];
            for (int val : a) count[val]++;
            for (int c : count) divisor *= IntegerUtils.factorial(c);
            out.printLine(res[0] / divisor);
        }
    }
    static class OutputWriter {
        private final PrintWriter writer;
        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }
        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }
        public void close() {
            writer.close();
        }
        public void printLine(long i) {
            writer.println(i);
        }
    }
    static class IntegerUtils {
        public static long factorial(int n) {
            long result = 1;
            for (int i = 2; i <= n; i++)
                result *= i;
            return result;
        }
    }
    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;
        public InputReader(InputStream stream) {
            this.stream = stream;
        }
        public int read() {
            if (numChars == -1)
                throw new InputMismatchException();
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }
        public int readInt() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }
        public String readString() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do {
                if (Character.isValidCodePoint(c))
                    res.appendCodePoint(c);
                c = read();
            } while (!isSpaceChar(c));
            return res.toString();
        }
        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return isWhitespace(c);
        }
        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }
        public String next() {
            return readString();
        }
        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Alex
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        TaskD solver = new TaskD();
        solver.solve(1, in, out);
        out.close();
    }
    static class TaskD {
        int[] a;
        int m;
        long[][] mem;
        long DONE;
        long[] dp(int used) {
            if (mem[used] != null) return mem[used];
            if (used == DONE) {
                long[] res = new long[m];
                res[0] = 1;
                return res;
            }
            int index = Integer.bitCount(used);
            long[] res = new long[m];
            for (int pos = 0; pos < a.length; pos++) {
                if (index == 0 && a[pos] == 0) continue;
                if (((used >> pos) & 1) != 0) continue;
                long[] get = dp(used | (1 << pos));
                int curval = (int) (IntegerUtils.power(10, a.length - index - 1) % m);
                for (int mod = 0; mod < get.length; mod++) {
                    res[(curval * a[pos] + mod) % m] += get[mod];
                }
            }
            return mem[used] = res;
        }
        public void solve(int testNumber, InputReader in, OutputWriter out) {
            char[] input = in.next().toCharArray();
            a = new int[input.length];
            for (int i = 0; i < a.length; i++) a[i] = (input[i] - '0');
            Arrays.sort(a);
            m = in.readInt();
            DONE = (1 << a.length) - 1;
            mem = new long[1 << a.length][];
            long[] res = dp(0);
            long divisor = 1;
            int[] count = new int[10];
            for (int val : a) count[val]++;
            for (int c : count) divisor *= IntegerUtils.factorial(c);
            out.printLine(res[0] / divisor);
        }
    }
    static class OutputWriter {
        private final PrintWriter writer;
        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }
        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }
        public void close() {
            writer.close();
        }
        public void printLine(long i) {
            writer.println(i);
        }
    }
    static class IntegerUtils {
        public static long factorial(int n) {
            long result = 1;
            for (int i = 2; i <= n; i++)
                result *= i;
            return result;
        }
        public static long power(long base, long exponent) {
            if (exponent == 0)
                return 1;
            long result = power(base, exponent >> 1);
            result = result * result;
            if ((exponent & 1) != 0)
                result = result * base;
            return result;
        }
    }
    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;
        public InputReader(InputStream stream) {
            this.stream = stream;
        }
        public int read() {
            if (numChars == -1)
                throw new InputMismatchException();
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }
        public int readInt() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }
        public String readString() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do {
                if (Character.isValidCodePoint(c))
                    res.appendCodePoint(c);
                c = read();
            } while (!isSpaceChar(c));
            return res.toString();
        }
        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return isWhitespace(c);
        }
        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }
        public String next() {
            return readString();
        }
        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
    }
}

import java.io.*;
import java.util.*;

public class D {
	FastScanner in = new FastScanner(System.in);
	PrintWriter out = new PrintWriter(System.out);

	int count(long x) {
		int res = 0;
		while (x > 0) {
			if (x % 2 != 0)
				res++;
			x /= 2;
		}
		return res;
	}

	public void run() {
		String s = in.next();
		int mod = in.nextInt();
		int len = s.length();

		long[][] dp = new long[(1<<len)][mod];
		int ten = (int)(Math.pow(10, len - 1) % mod);
		for (int i = 0; i < len; i++) {
			int c = s.charAt(i) - '0';
			if (c != 0) dp[(1 << i)][(c * ten) % mod] = 1;
		}

		for (int pos = 1; pos < len; pos++) {
			ten = (int)(Math.pow(10, len - pos - 1) % mod);
			for (int i = 0; i < (1 << len); i++) {
				if (count(i) != pos) continue;
				for (int j = 0; j < len; j++) {
					if ((i & (1 << j)) != 0) continue;
					int c = s.charAt(j) - '0';
					int next = i | (1 << j);
					for (int k = 0; k < mod; k++) {
						dp[next][(k + c * ten) % mod] += dp[i][k];
					}
				}
			}
		}

		long res = dp[(1<<len) - 1][0];
		int[] cnt = new int[10];
		for (int i = 0; i < len; i++) {
			cnt[s.charAt(i) - '0']++;
		}
		for (int i = 0; i < 10; i++) {
			for (int j = cnt[i]; j >= 2; j--) {
				res /= j;
			}
		}
		System.out.println(res);

		out.close();
	}

	public static void main(String[] args) {
		new D().run();
	}

	public void mapDebug(int[][] a) {
		System.out.println("--------map display---------");

		for (int i = 0; i < a.length; i++) {
			for (int j = 0; j < a[i].length; j++) {
				System.out.printf("%3d ", a[i][j]);
			}
			System.out.println();
		}

		System.out.println("----------------------------");
		System.out.println();
	}

	public void debug(Object... obj) {
		System.out.println(Arrays.deepToString(obj));
	}

	class FastScanner {
		private InputStream stream;
		private byte[] buf = new byte[1024];
		private int curChar;
		private int numChars;

		public FastScanner(InputStream stream) {
			this.stream = stream;
			//stream = new FileInputStream(new File("dec.in"));

		}

		int read() {
			if (numChars == -1)
				throw new InputMismatchException();
			if (curChar >= numChars) {
				curChar = 0;
				try {
					numChars = stream.read(buf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (numChars <= 0)
					return -1;
			}
			return buf[curChar++];
		}

		boolean isSpaceChar(int c) {
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		boolean isEndline(int c) {
			return c == '\n' || c == '\r' || c == -1;
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		int[] nextIntArray(int n) {
			int[] array = new int[n];
			for (int i = 0; i < n; i++)
				array[i] = nextInt();

			return array;
		}

		int[][] nextIntMap(int n, int m) {
			int[][] map = new int[n][m];
			for (int i = 0; i < n; i++) {
				map[i] = in.nextIntArray(m);
			}
			return map;
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		long[] nextLongArray(int n) {
			long[] array = new long[n];
			for (int i = 0; i < n; i++)
				array[i] = nextLong();

			return array;
		}

		long[][] nextLongMap(int n, int m) {
			long[][] map = new long[n][m];
			for (int i = 0; i < n; i++) {
				map[i] = in.nextLongArray(m);
			}
			return map;
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}

		double[] nextDoubleArray(int n) {
			double[] array = new double[n];
			for (int i = 0; i < n; i++)
				array[i] = nextDouble();

			return array;
		}

		double[][] nextDoubleMap(int n, int m) {
			double[][] map = new double[n][m];
			for (int i = 0; i < n; i++) {
				map[i] = in.nextDoubleArray(m);
			}
			return map;
		}

		String next() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		String[] nextStringArray(int n) {
			String[] array = new String[n];
			for (int i = 0; i < n; i++)
				array[i] = next();

			return array;
		}

		String nextLine() {
			int c = read();
			while (isEndline(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isEndline(c));
			return res.toString();
		}
	}
}

import java.io.*;
import java.util.*;

public class D {
	FastScanner in = new FastScanner(System.in);
	PrintWriter out = new PrintWriter(System.out);

	int count(long x) {
		int res = 0;
		while (x > 0) {
			if (x % 2 != 0)
				res++;
			x /= 2;
		}
		return res;
	}

	public void run() {
		String s = in.next();
		int mod = in.nextInt();
		int len = s.length();

		long[][] dp = new long[(1<<len)][mod];
		int ten = (int)(Math.pow(10, len - 1) % mod);
		for (int i = 0; i < len; i++) {
			int c = s.charAt(i) - '0';
			if (c != 0) dp[(1 << i)][(c * ten) % mod] = 1;
		}

		for (int i = 0; i < (1 << len); i++) {
			int pos = count(i);
			ten = (int)(Math.pow(10, len - pos - 1) % mod);
			for (int k = 0; k < mod; k++) {
				if (dp[i][k] == 0) continue;
				for (int j = 0; j < len; j++) {
					if ((i & (1 << j)) != 0) continue;
					int c = s.charAt(j) - '0';
					int next = i | (1 << j);
					dp[next][(k + c * ten) % mod] += dp[i][k];
				}
			}
		}

		long res = dp[(1<<len) - 1][0];
		int[] cnt = new int[10];
		for (int i = 0; i < len; i++) {
			cnt[s.charAt(i) - '0']++;
		}
		for (int i = 0; i < 10; i++) {
			for (int j = cnt[i]; j >= 2; j--) {
				res /= j;
			}
		}
		System.out.println(res);

		out.close();
	}

	public static void main(String[] args) {
		new D().run();
	}

	public void mapDebug(int[][] a) {
		System.out.println("--------map display---------");

		for (int i = 0; i < a.length; i++) {
			for (int j = 0; j < a[i].length; j++) {
				System.out.printf("%3d ", a[i][j]);
			}
			System.out.println();
		}

		System.out.println("----------------------------");
		System.out.println();
	}

	public void debug(Object... obj) {
		System.out.println(Arrays.deepToString(obj));
	}

	class FastScanner {
		private InputStream stream;
		private byte[] buf = new byte[1024];
		private int curChar;
		private int numChars;

		public FastScanner(InputStream stream) {
			this.stream = stream;
			//stream = new FileInputStream(new File("dec.in"));

		}

		int read() {
			if (numChars == -1)
				throw new InputMismatchException();
			if (curChar >= numChars) {
				curChar = 0;
				try {
					numChars = stream.read(buf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (numChars <= 0)
					return -1;
			}
			return buf[curChar++];
		}

		boolean isSpaceChar(int c) {
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		boolean isEndline(int c) {
			return c == '\n' || c == '\r' || c == -1;
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		int[] nextIntArray(int n) {
			int[] array = new int[n];
			for (int i = 0; i < n; i++)
				array[i] = nextInt();

			return array;
		}

		int[][] nextIntMap(int n, int m) {
			int[][] map = new int[n][m];
			for (int i = 0; i < n; i++) {
				map[i] = in.nextIntArray(m);
			}
			return map;
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		long[] nextLongArray(int n) {
			long[] array = new long[n];
			for (int i = 0; i < n; i++)
				array[i] = nextLong();

			return array;
		}

		long[][] nextLongMap(int n, int m) {
			long[][] map = new long[n][m];
			for (int i = 0; i < n; i++) {
				map[i] = in.nextLongArray(m);
			}
			return map;
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}

		double[] nextDoubleArray(int n) {
			double[] array = new double[n];
			for (int i = 0; i < n; i++)
				array[i] = nextDouble();

			return array;
		}

		double[][] nextDoubleMap(int n, int m) {
			double[][] map = new double[n][m];
			for (int i = 0; i < n; i++) {
				map[i] = in.nextDoubleArray(m);
			}
			return map;
		}

		String next() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		String[] nextStringArray(int n) {
			String[] array = new String[n];
			for (int i = 0; i < n; i++)
				array[i] = next();

			return array;
		}

		String nextLine() {
			int c = read();
			while (isEndline(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isEndline(c));
			return res.toString();
		}
	}
}

import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

public class P401D
{
	static long[][] dp;
	public static void main(String[] args)
	{
		Scanner scan = new Scanner(System.in);
		char[] n = scan.next().toCharArray();
		for (int i = 0; i < n.length; i++)
			n[i] -= '0';
		int m = scan.nextInt();
		dp = new long[1 << n.length][m];
		Integer[] nums = new Integer[1 << n.length];
		for (int i = 0; i < nums.length; i++)
			nums[i] = i;
		Arrays.sort(nums, new Comparator<Integer>() {
			public int compare(Integer a, Integer b) {
				return Integer.bitCount(a) - Integer.bitCount(b);
			}
		});
		dp[0][0] = 1;
		for (int i = 0; i < nums.length; i++)
		{
			int num = nums[i];
			int bits = Integer.bitCount(num);
			for (int j = 0; j < m; j++)
			{
				if (dp[num][j] == 0)
					continue;
				boolean[] done = new boolean[10];
				for (int k = 0; k < n.length; k++)
				{
					if ((num & (1 << k)) == 0)
					{
						int d = n[k];
						if (done[d])
							continue;
						if (d == 0 && bits == 0)
							continue;
						dp[num | (1 << k)][(j*10+d)%m] += dp[num][j];
						done[d] = true;
					}
				}
			}
		}
		System.out.println(dp[dp.length-1][0]);
	}
}

import java.io.*;
import java.util.*;
import java.math.*;

public class Main {

    long[][] dp;
    char[] str;
    int n;
    int m;

    public void solve() throws IOException{

        str = in.next().toCharArray();
        n = str.length;
        m = in.nextInt();
        dp = new long[(int) 1L << n][(int) m];
        for(int i = 0; i < dp.length; i++){
            for(int j = 0; j < dp[0].length; j++){
                dp[i][j] = -1;
            }
        }

        long res = dfs(0, 0);
        out.println(res);
        return;
    }

    public long dfs(int mask, int mod){

        if(dp[mask][mod] != -1){
            return dp[mask][mod];
        }else if(mask == dp.length - 1 && mod == 0){
            return 1;
        }else if(mask == dp.length - 1 && mod != 0){
            return 0;
        }

        dp[mask][mod] = 0L;
        Set<Integer> used = new HashSet<>();

        for(int i = 0; i < n; i++){

            if((mask | (1 << i)) != mask && !used.contains(str[i] - '0') && (mask > 0 || str[i] != '0')){

                dp[mask][mod] += dfs(mask | (1 << i), (mod * 10 + (str[i] - '0')) % m);
                used.add(str[i] - '0');

            }
        }

        return dp[mask][mod];
    }

    public BigInteger gcdBigInt(BigInteger a, BigInteger b){

        if(a.compareTo(BigInteger.valueOf(0L)) == 0){
            return b;
        }else{
            return gcdBigInt(b.mod(a), a);
        }

    }

    FastScanner in;
    PrintWriter out;

    static class FastScanner {

        BufferedReader br;
        StringTokenizer st;

        FastScanner(InputStream in) {
            br = new BufferedReader(new InputStreamReader(in));
            st = null;
        }

        String next() throws IOException {
            while (st == null || !st.hasMoreTokens())
                st = new StringTokenizer(br.readLine());
            return st.nextToken();
        }

        String nextLine() throws IOException {
            if (st == null || !st.hasMoreTokens())
                return br.readLine();
            StringBuilder result = new StringBuilder(st.nextToken());
            while (st.hasMoreTokens()) {
                result.append(" ");
                result.append(st.nextToken());
            }
            return result.toString();
        }

        int nextInt() throws IOException {
            return Integer.parseInt(next());
        }

        long nextLong() throws IOException {
            return Long.parseLong(next());
        }

        double nextDouble() throws IOException {
            return Double.parseDouble(next());
        }

    }

    void run() throws IOException {
        in = new FastScanner(System.in);
        out = new PrintWriter(System.out, false);
        solve();
        out.close();
    }

    public static void main(String[] args) throws IOException{
        new Main().run();
    }

    public void printArr(int[] arr){
        for(int i = 0; i < arr.length; i++){
            out.print(arr[i] + " ");
        }
        out.println();
    }

    public long gcd(long a, long b){
        if(a == 0) return b;
        return gcd(b % a, a);
    }

    public boolean isPrime(long num){

        if(num == 0 || num == 1){
            return false;
        }

        for(int i = 2; i * i <= num; i++){
            if(num % i == 0){
                return false;
            }
        }

        return true;
    }

    public class Pair<A, B>{
        public A x;
        public B y;

        Pair(A x, B y){
            this.x = x;
            this.y = y;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Pair<?, ?> pair = (Pair<?, ?>) o;
            if (!x.equals(pair.x)) return false;
            return y.equals(pair.y);
        }

        @Override
        public int hashCode() {
            int result = x.hashCode();
            result = 31 * result + y.hashCode();
            return result;
        }

    }

    class Tuple{
        int x; int y; int z;
        Tuple(int ix, int iy, int iz){
            x = ix;
            y = iy;
            z = iz;
        }
    }
}

import java.io.*;
import java.util.*;

public class Main {

    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        String n1 = in.next();
        String n2 = in.next();
        int m = Integer.parseInt(n2);
        int[] count = new int[10];
        Arrays.fill(count, 0);
        for (int i = 0; i < n1.length(); i++) {
            count[n1.charAt(i) - '0']++;
        }
        long[] f = new long[19];
        f[0] = 1;
        for (int i = 1; i < 19; i++) {
            f[i] = f[i - 1] * i;
        }
        int sh = 1 << n1.length();
        long[][] dp = new long[sh][m];
        for (int s = 0; s < sh; s++) {
            Arrays.fill(dp[s], 0);
        }
        dp[0][0] = 1;
        for (int i = 0; i < sh; i++) {
            for (int j = 0; j < n1.length(); j++) {
                int now = n1.charAt(j) - '0';
                if ((now == 0 && i == 0) || (i & (1 << j)) != 0) {
                    continue;
                }
                for (int k = 0; k < m; k++) {
                    if (dp[i][k] > 0) {
                        int i1 = i | (1 << j);
                        int i2 = (10 * k + now) % m;
                        dp[i1][i2] += dp[i][k];
                    }
                }
            }
        }
        long x = dp[sh - 1][0];
        for (int i = 0; i <= 9; i++) {
            x /= f[count[i]];
        }
        out.println(x);
        out.close();
    }

    static class InputReader {

        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }

}

import java.io.*;
import java.lang.*;
import java.util.*;

public class Main {

  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    PrintWriter out = new PrintWriter(System.out);
    new Task().solve(scanner, out);
    scanner.close();
    out.close();
  }
}

class Task {

  public void solve(Scanner in, PrintWriter out) {
    String bigNumber = in.next();
    int mod = in.nextInt();
    int n = bigNumber.length();
    int maxMask = (1 << n) - 1;
    double dp[][] = new double[maxMask + 1][mod];
    for (int k = 0; k < n; k++) {
      int bit = 1 << k;
      if ('0' != bigNumber.charAt(k))
        dp[bit][(bigNumber.charAt(k) - '0') % mod] = 1;
    }
    for (int i = 0; i < maxMask; i++) {
      for (int j =0; j < mod; j++) {
        for (int k = 0; k < n; k++) {
          int bit = 1 << k;
          if (0 == (i & bit)) {
            dp[i | bit][(j * 10 + (bigNumber.charAt(k) - '0')) % mod] += dp[i][j];
          }
        }
      }
    }
    int[] count = new int[10];
    for (int i =0; i < n; i++) {
      count[bigNumber.charAt(i) - '0']++;
    }
    double result = dp[maxMask][0];
    for (int i=0; i < 10; i++) {
      for (int j=1; j <= count[i]; j++) {
        result = result / j;
      }
    }
    out.println((long) result);
  }
}

import java.util.*;
import java.io.*;
public class RomanandNumbers {

    /************************ SOLUTION STARTS HERE ************************/

    static int mod;
    static int digits[];
    static long memo[][];

    static long rec(int mask , int sum) {
        if(Integer.bitCount(mask) == digits.length)
            return sum == 0 ? 1 : 0;
        else if(memo[mask][sum] != -1)
            return memo[mask][sum];
        else {
            long ways = 0;
            int used = 0;
            for(int i = 0; i < digits.length; i++)
                if((mask & (1 << i)) == 0) {
                    if(mask == 0 && digits[i] == 0) // first digit is 0
                        continue;
                    if((used & (1 << digits[i])) != 0) // digit already used
                        continue;

                    used |= 1 << digits[i];
                    ways += rec(mask | (1 << i), (sum * 10 + digits[i]) % mod);
                }

            return memo[mask][sum] = ways;
        }
    }

    private static void solve() {

        long n = nextLong();
        mod = nextInt();
        digits = String.valueOf(n).chars().map(Character::getNumericValue).toArray();

        memo = new long[1 << digits.length][mod];
        for(long t[] : memo) Arrays.fill(t, -1);

        println(rec(0, 0));
    }

    /************************ SOLUTION ENDS HERE ************************/

    /************************ TEMPLATE STARTS HERE **********************/

    public static void main(String[] args) throws IOException {
        reader = new BufferedReader(new InputStreamReader(System.in));
        writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false);
        st     = null;
        solve();
        reader.close();
        writer.close();
    }

    static BufferedReader reader;
    static PrintWriter    writer;
    static StringTokenizer st;

    static String next()
    {while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;}
    st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();}
    static String nextLine()  {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;}
    static int    nextInt()   {return Integer.parseInt(next());}
    static long   nextLong()  {return Long.parseLong(next());}
    static double nextDouble(){return Double.parseDouble(next());}
    static char   nextChar()  {return next().charAt(0);}
    static int[]  nextIntArray(int n)         {int[] a= new int[n];   int i=0;while(i<n){a[i++]=nextInt();}  return a;}
    static long[] nextLongArray(int n)        {long[]a= new long[n];  int i=0;while(i<n){a[i++]=nextLong();} return a;}
    static int[]  nextIntArrayOneBased(int n) {int[] a= new int[n+1]; int i=1;while(i<=n){a[i++]=nextInt();} return a;}
    static long[] nextLongArrayOneBased(int n){long[]a= new long[n+1];int i=1;while(i<=n){a[i++]=nextLong();}return a;}
    static void   print(Object o)  { writer.print(o);  }
    static void   println(Object o){ writer.println(o);}

    /************************ TEMPLATE ENDS HERE ************************/

}

import java.awt.*;
import java.io.*;
import java.util.*;

public class Abc {
    static long dp[][];
    static int dig[];
    static int n;
    static int r;
    static int m;
    public static void main(String[] args) {
        FastReader sc = new FastReader();
        String s=sc.next();m=sc.nextInt();
        n=s.length();
        r=(1<<n)-1;
        dig=new int[n];
//        int repeat[]=new int[10];
        for (int i=0;i<n;i++){
            dig[i]=s.charAt(i)-'0';
//            repeat[dig[i]]++;
        }
        Arrays.sort(dig);
        dp=new long[r+1][m];
        for (long arr[]:dp)Arrays.fill(arr,-1);
        long ans=dp(0,0);
        System.out.println(ans);
    }

    static long dp(int mask,int rem){
        if (mask==r){
            if (rem==0)return 1;
        }
        if (dp[mask][rem]!=-1)return dp[mask][rem];
        long ans=0;
        for (int i=0;i<n;i++){
            if (i>0 && ((mask&(1<<(i-1))))==0 && dig[i-1]==dig[i])continue;
            if ((mask&(1<<i))==0 && (mask!=0 || dig[i]!=0)){
                ans+=dp((mask|(1<<i)),(10*rem+dig[i])%m);
            }
        }
        return dp[mask][rem]=ans;
    }
    static class FastReader {
        BufferedReader br;
        StringTokenizer st;

        public FastReader() {
            br = new BufferedReader(new
                    InputStreamReader(System.in));
        }

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }

        String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }
}

import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.text.*;

public class cf401D {

    static BufferedReader br;
    static Scanner sc;
    static PrintWriter out;

    public static void initA() {
        try {
            br = new BufferedReader(new InputStreamReader(System.in));
            sc = new Scanner(System.in);
            out = new PrintWriter(System.out);
        } catch (Exception e) {
        }
    }

    static boolean next_permutation(Integer[] p) {
        for (int a = p.length - 2; a >= 0; --a) {
            if (p[a] < p[a + 1]) {
                for (int b = p.length - 1;; --b) {
                    if (p[b] > p[a]) {
                        int t = p[a];
                        p[a] = p[b];
                        p[b] = t;
                        for (++a, b = p.length - 1; a < b; ++a, --b) {
                            t = p[a];
                            p[a] = p[b];
                            p[b] = t;
                        }
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public static String getString() {
        try {
            return br.readLine();
        } catch (Exception e) {
        }
        return "";
    }

    public static Integer getInt() {
        try {
            return Integer.parseInt(br.readLine());
        } catch (Exception e) {
        }
        return 0;
    }

    public static Integer[] getIntArr() {
        try {
            StringTokenizer temp = new StringTokenizer(br.readLine());
            int n = temp.countTokens();
            Integer temp2[] = new Integer[n];
            for (int i = 0; i < n; i++) {
                temp2[i] = Integer.parseInt(temp.nextToken());
            }
            return temp2;
        } catch (Exception e) {
        }
        return null;
    }

    public static Long[] getLongArr() {
        try {
            StringTokenizer temp = new StringTokenizer(br.readLine());
            int n = temp.countTokens();
            Long temp2[] = new Long[n];
            for (int i = 0; i < n; i++) {
                temp2[i] = Long.parseLong(temp.nextToken());
            }
            return temp2;
        } catch (Exception e) {
        }
        return null;
    }

    public static String[] getStringArr() {
        try {
            StringTokenizer temp = new StringTokenizer(br.readLine());
            int n = temp.countTokens();
            String temp2[] = new String[n];
            for (int i = 0; i < n; i++) {
                temp2[i] = (temp.nextToken());
            }
            return temp2;
        } catch (Exception e) {
        }
        return null;
    }

    public static void print(Object a) {
        System.out.println(a);
    }

    public static void print(String s, Object... a) {
        System.out.printf(s, a);
    }

    public static int nextInt() {
        return sc.nextInt();
    }

    public static double nextDouble() {
        return sc.nextDouble();
    }

    public static void main(String[] ar) {
        initA();
        cf401D c = new cf401D();
        c.solve();
        out.flush();
    }
    int inp[] = new int[25];
    int n;
    short moder;

    void solve() {
        String in[] = getStringArr();
        char cb[] = in[0].toCharArray();
        n = cb.length;
        int ct[] = new int[10];
        for (int i = 0; i < n; i++) {
            inp[i] = cb[i] - '0';
            ct[inp[i]]++;
        }

        moder = Short.valueOf(in[1]);

        //print(100 * 100 * (1<<18) * 20);

        int end = (1 << (n));
        //print(end+" "+Integer.toString(end,2));
        long bef[][] = new long[end][100];
        bef[0][0] = 1;
        int bit[] = new int[end];
        for (int i = 0; i < end; i++) {
            int num =  0;
            int tv = i;
            while(tv > 0){
                if(tv%2==1){
                    num++;
                }
                tv/=2;
            }

            bit[i] = num;
        }
        for (int i = 1; i <= n; i++) {

            for (int k = 0; k < end; k++) {
                if(bit[k]!=i-1)continue;
                for (int j = 0; j < moder; j++) {

                    if (bef[k][j] > 0) {
                        for (int l = 0; l < n; l++) {
                            if ((k & (1 << l)) == 0) {
                                if (i == 1 && inp[l] == 0) {
                                    continue;
                                }
                                int nv = (j * 10 + inp[l]) % moder;
                                int nb = k | (1 << l);
                                //print("SEBELUM ERROR" + nv+" "+nb);
                                bef[nb][nv] += bef[k][j];
                                //print(nv + " " + Integer.toString(nb, 2) + " = " + bef[nb][nv]);
                            }
                        }
                    }
                }
            }

        }
        long ou = bef[end - 1][0];
        //print(ou);
        for (int i = 0; i < 10; i++) {
            ou /= fact(ct[i]);
        }
        print(ou);

    }

    long fact(int n) {
        if (n <= 1) {
            return 1;
        }
        return fact(n - 1) * n;
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.io.InputStream;

/**
 * @author khokharnikunj8
 */

public class Main {
    public static void main(String[] args) {
        new Thread(null, new Runnable() {
            public void run() {
                new Main().solve();
            }
        }, "1", 1 << 26).start();
    }

    void solve() {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        ScanReader in = new ScanReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        DRomanAndNumbers solver = new DRomanAndNumbers();
        solver.solve(1, in, out);
        out.close();
    }

    static class DRomanAndNumbers {
        public void solve(int testNumber, ScanReader in, PrintWriter out) {
            char[] s = in.scanString().toCharArray();
            int m = in.scanInt();
            int n = s.length;
            long[][] dp = new long[1 << n][m];
            for (int i = 0; i < n; i++) {
                if (s[i] != '0') dp[1 << i][(s[i] - '0') % m] = 1;
            }
            int[] si = new int[n];
            for (int i = 0; i < n; i++) si[i] = s[i] - '0';
            long[] fact = new long[20];
            fact[0] = 1;
            for (int i = 1; i < 20; i++) fact[i] = fact[i - 1] * i;
            for (int i = 1; i < 1 << n; i++) {
                for (int j = 0; j < m; j++) {
                    if (dp[i][j] == 0) continue;
                    for (int k = 0; k < n; k++) {
                        if ((i & (1 << k)) == 0) {
                            dp[i ^ (1 << k)][(j * 10 + (si[k])) % m] += dp[i][j];
                        }
                    }
                }
            }
            long ans = dp[(1 << n) - 1][0];
            int[] count = new int[10];
            for (char c : s) count[c - '0']++;
            for (int i : count) ans /= fact[i];
            out.println(ans);

        }

    }

    static class ScanReader {
        private byte[] buf = new byte[4 * 1024];
        private int index;
        private BufferedInputStream in;
        private int total;

        public ScanReader(InputStream inputStream) {
            in = new BufferedInputStream(inputStream);
        }

        private int scan() {
            if (index >= total) {
                index = 0;
                try {
                    total = in.read(buf);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (total <= 0) return -1;
            }
            return buf[index++];
        }

        public int scanInt() {
            int integer = 0;
            int n = scan();
            while (isWhiteSpace(n)) n = scan();
            int neg = 1;
            if (n == '-') {
                neg = -1;
                n = scan();
            }
            while (!isWhiteSpace(n)) {
                if (n >= '0' && n <= '9') {
                    integer *= 10;
                    integer += n - '0';
                    n = scan();
                }
            }
            return neg * integer;
        }

        public String scanString() {
            int c = scan();
            if (c == -1) return null;
            while (isWhiteSpace(c)) c = scan();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = scan();
            } while (!isWhiteSpace(c));
            return res.toString();
        }

        private boolean isWhiteSpace(int n) {
            if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
            else return false;
        }

    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.io.InputStream;

/**
 * @author khokharnikunj8
 */

public class Main {
    public static void main(String[] args) {
        new Thread(null, new Runnable() {
            public void run() {
                new Main().solve();
            }
        }, "1", 1 << 26).start();
    }

    void solve() {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        ScanReader in = new ScanReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        DRomanAndNumbers solver = new DRomanAndNumbers();
        solver.solve(1, in, out);
        out.close();
    }

    static class DRomanAndNumbers {
        public void solve(int testNumber, ScanReader in, PrintWriter out) {
            char[] s = in.scanString().toCharArray();
            int m = in.scanInt();
            long[][] dp = new long[1 << s.length][m];
            for (int i = 0; i < s.length; i++) {
                if (s[i] != '0') dp[1 << i][(s[i] - '0') % m] = 1;
            }
            int[] si = new int[s.length];
            for (int i = 0; i < s.length; i++) si[i] = s[i] - '0';
            long[] fact = new long[20];
            fact[0] = 1;
            for (int i = 1; i < 20; i++) fact[i] = fact[i - 1] * i;
            for (int i = 1; i < 1 << s.length; i++) {
                for (int j = 0; j < m; j++) {
                    if (dp[i][j] == 0) continue;
                    for (int k = 0; k < s.length; k++) {
                        if ((i & (1 << k)) == 0) {
                            dp[i ^ (1 << k)][(j * 10 + (si[k])) % m] += dp[i][j];
                        }
                    }
                }
            }
            long ans = dp[(1 << s.length) - 1][0];
            int[] count = new int[10];
            for (char c : s) count[c - '0']++;
            for (int i : count) ans /= fact[i];
            out.println(ans);

        }

    }

    static class ScanReader {
        private byte[] buf = new byte[4 * 1024];
        private int index;
        private BufferedInputStream in;
        private int total;

        public ScanReader(InputStream inputStream) {
            in = new BufferedInputStream(inputStream);
        }

        private int scan() {
            if (index >= total) {
                index = 0;
                try {
                    total = in.read(buf);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (total <= 0) return -1;
            }
            return buf[index++];
        }

        public int scanInt() {
            int integer = 0;
            int n = scan();
            while (isWhiteSpace(n)) n = scan();
            int neg = 1;
            if (n == '-') {
                neg = -1;
                n = scan();
            }
            while (!isWhiteSpace(n)) {
                if (n >= '0' && n <= '9') {
                    integer *= 10;
                    integer += n - '0';
                    n = scan();
                }
            }
            return neg * integer;
        }

        public String scanString() {
            int c = scan();
            if (c == -1) return null;
            while (isWhiteSpace(c)) c = scan();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = scan();
            } while (!isWhiteSpace(c));
            return res.toString();
        }

        private boolean isWhiteSpace(int n) {
            if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
            else return false;
        }

    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;

public class D {
    static long n;
    static int m;

    static int cnt_bits(int i) {
        int ret=0;
        while(i>0) {
            ret++;
            i-=Integer.lowestOneBit(i);
        }
        return ret;
    }

    static int digit(char[] s, int i) {
        return s[i]-'0';
    }

    static int pos(int i) {
        int ret=-1;
        while(i>0) {
            ret++;
            i=i>>1;
        }

        return ret;
    }

    static long fac(int i) {
        long ret=1;
        for (int j=2; j<=i; j++) {
            ret*=j;
        }
        return ret;
    }

    static long solve() {
        char[] s=Long.toString(n).toCharArray();
        Arrays.sort(s);

        int l=s.length, k=(1<<l)-1;

        Integer[] sets=new Integer[k+1];
        for (int i=0; i<=k; i++) {
            sets[i]=i;
        }
        Arrays.sort(sets, new Comparator<Integer>() {
            public int compare(Integer o1, Integer o2) {
                int i1=cnt_bits(o1), i2=cnt_bits(o2);
                return i1-i2;
            }});

        long[][] f=new long[k+1][m];
        for (int i=0; i<l; i++) {
            int d=digit(s, i);
            if(d>0) {
                f[1<<i][d%m]=1;
            }
        }

        for (int i=0; i<=k; i++) {
            int set=sets[i], bcnt=cnt_bits(set), set2=set;
            for (int j=0; j<bcnt; j++) {
                int lo=Integer.lowestOneBit(set2), loidx=pos(lo);
                set2-=lo;
                for (int r=0; r<m; r++) {
                    if(f[set-lo][r]>0) {
                        int r2=(10*r+digit(s,loidx))%m;
                        f[set][r2]+=f[set-lo][r];
                    }
                }
            }
        }

        int[] perms=new int[10];
        for (int i=0; i<s.length; i++) {
            perms[digit(s,i)]++;
        }
        long p=1;
        for (int i=0; i<perms.length; i++) {
            p*=fac(perms[i]);
        }

        return f[k][0]/p;
    }

    static void run_stream(InputStream ins) throws IOException {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

        String[] nm=br.readLine().split(" ");
        n=Long.parseLong(nm[0]);
        m=Integer.parseInt(nm[1]);

        System.out.println(solve());

    }

    public static void main(String[] args) throws IOException {
        run_stream(System.in);
    }

}

import java.io.IOException;
import java.util.Arrays;
import java.io.UnsupportedEncodingException;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		PrintWriter out = new PrintWriter(outputStream);
		TaskD solver = new TaskD();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskD {
	long n;
	int m;
	String nn;
	long dp[][] = new long[(1 << 18) + 1][100];
	public void solve(int testNumber, InputReader in, PrintWriter out) {

		n = in.readLong();
		m = in.readInt();
		nn = "" + n;
		if(n == (long)1e18) {
			out.println(n % m == 0? 1 : 0);
			return;
		}
		int c[] = new int[10];
		for(int i = 0;i < nn.length();i++) {
			c[nn.charAt(i) - '0']++;
		}
		long ct = 0;
		for(int i = 0;i < dp.length;i++) {
			Arrays.fill(dp[i], -1);
		}
		ct = count(0, 0);
		out.println(ct);

    }

	public long count(int mask, int r) {
		if(dp[mask][r] != -1) return dp[mask][r];
		if(mask == (1 << nn.length()) - 1) {
			if(r == 0) return 1;
			else return 0;
		}
		long count = 0;
		boolean isUsed[] = new boolean[10];
		for(int i  = 0;i < nn.length();i++) {
			if(isUsed[nn.charAt(i) - '0']) continue;
			if(mask == 0 && nn.charAt(i) == '0') continue;
			if((mask & (1 << i)) == 0) {

				isUsed[nn.charAt(i) - '0'] = true;
				count += count(mask | (1 << i), (r*10 + (nn.charAt(i) - '0')) % m);
			}
		}
		return dp[mask][r] = count;
	}

}

class InputReader {

    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;

    public InputReader(InputStream stream) {
        this.stream = stream;
    }

    public int read() {
        if (numChars == -1)
            throw new InputMismatchException();
        if (curChar >= numChars) {
            curChar = 0;
            try {
                numChars = stream.read(buf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (numChars <= 0)
                return -1;
        }
        return buf[curChar++];
    }

    public int readInt() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        int res = 0;
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

    public long readLong() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        long res = 0;
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

    public static boolean isSpaceChar(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    }

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.io.InputStream;

/**
 * @author khokharnikunj8
 */

public class Main {
    public static void main(String[] args) {
        new Thread(null, new Runnable() {
            public void run() {
                new Main().solve();
            }
        }, "1", 1 << 26).start();
    }

    void solve() {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        ScanReader in = new ScanReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        DRomanAndNumbers solver = new DRomanAndNumbers();
        solver.solve(1, in, out);
        out.close();
    }

    static class DRomanAndNumbers {
        public void solve(int testNumber, ScanReader in, PrintWriter out) {
            char[] s = in.scanString().toCharArray();
            int m = in.scanInt();
            int n = s.length;
            int[] si = new int[n];
            for (int i = 0; i < n; i++) si[i] = s[i] - '0';
            Arrays.sort(si);

            long[][] dp = new long[1 << n][m];
            dp[0][0] = 1;
            for (int i = 0; i < 1 << n; i++) {
                for (int j = 0; j < m; j++) {
                    if (dp[i][j] == 0) continue;
                    for (int k = 0; k < n; k++) {
                        if ((i & 1 << k) == 0) {
                            if (i == 0 && si[k] == 0) continue;
                            if (k > 0 && si[k] == si[k - 1] && (i & 1 << k - 1) == 0) continue;
                            dp[i | 1 << k][(j * 10 + si[k]) % m] += dp[i][j];
                        }
                    }
                }
            }
            out.println(dp[(1 << n) - 1][0]);

        }

    }

    static class ScanReader {
        private byte[] buf = new byte[4 * 1024];
        private int index;
        private BufferedInputStream in;
        private int total;

        public ScanReader(InputStream inputStream) {
            in = new BufferedInputStream(inputStream);
        }

        private int scan() {
            if (index >= total) {
                index = 0;
                try {
                    total = in.read(buf);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (total <= 0) return -1;
            }
            return buf[index++];
        }

        public int scanInt() {
            int integer = 0;
            int n = scan();
            while (isWhiteSpace(n)) n = scan();
            int neg = 1;
            if (n == '-') {
                neg = -1;
                n = scan();
            }
            while (!isWhiteSpace(n)) {
                if (n >= '0' && n <= '9') {
                    integer *= 10;
                    integer += n - '0';
                    n = scan();
                }
            }
            return neg * integer;
        }

        public String scanString() {
            int c = scan();
            if (c == -1) return null;
            while (isWhiteSpace(c)) c = scan();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = scan();
            } while (!isWhiteSpace(c));
            return res.toString();
        }

        private boolean isWhiteSpace(int n) {
            if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
            else return false;
        }

    }
}

import java.io.*;
import java.util.*;

public class p401d {
    BufferedReader in;
    PrintWriter out;
    StringTokenizer st;

    String next() {
        while (st == null || !st.hasMoreTokens()) {
            try {
                st = new StringTokenizer(in.readLine());
            } catch (Exception e) {
            }
        }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    long nextLong() {
        return Long.parseLong(next());
    }

    double nextDouble() {
        return Double.parseDouble(next());
    }

    public long[][] d = new long[1 << 18][102];
    public int cnt[] = new int[11];
    public int f[] = new int[20];

    public long ans = 0;

    public void run() throws Exception {
        in = new BufferedReader(new InputStreamReader(System.in));
        // in = new BufferedReader(new FileReader(new File("./src/input.txt")));
        out = new PrintWriter(System.out);

        long n = nextLong();
        int m = nextInt();
        int len = 0;

        while (n > 0) {
            cnt[(int) (n % 10)]++;
            f[len++] = (int) (n % 10);
            n /= 10;
        }

        for (int i = 0; i < len; i++)
            if (f[i] > 0) {
                d[1 << i][f[i] % m] += 1;
            }

        for (int i = 1; i < (1 << len); i++) {
            for (int j = 0; j < m; j++) {
                if (d[i][j] == 0) {
                    continue;
                }
                for (int p = 0; p < len; p++) {
                    if ((i & (1 << p)) == 0) {
                        d[i | (1 << p)][(j * 10 + f[p]) % m] += d[i][j];
                    }
                }
            }
        }

        long ans = d[(1 << len)-1][0];

        for (int i = 0; i<10; i++)
            for (int j = 1; j<=cnt[i]; j++)
                ans/=j;

        out.println(ans);

        out.close();
    }

    public static void main(String[] args) throws Exception {
        new p401d().run();
    }

}

import java.io.*;
import java.util.*;

public class cf401d {
  static FastIO in = new FastIO(), out = in;

  static int n, MOD;
  static int[] v;
  static long[][] memo;
  public static void main(String[] args) {
    String x = in.next().trim();
    n = x.length();
    v = new int[n];
    for(int i=0; i<n; i++) {
      v[i] = x.charAt(i)-'0';
    }
    MOD = in.nextInt();
    memo = new long[MOD][1<<n];
    for(long[] z : memo) Arrays.fill(z, -1L);
    out.println(go(0,0));
    out.close();
  }
  static long go(int mask, int mod) {
    if(memo[mod][mask] != -1) return memo[mod][mask];
    if(mask == (1<<n)-1) return mod == 0 ? 1 : 0;
    long ret = 0;
    boolean[] tried = new boolean[10];
    for(int i=0; i<n; i++)
      if((mask&(1<<i)) == 0) {
        if(tried[v[i]]) continue;
        tried[v[i]] = true;
        if(mask == 0 && v[i] == 0) continue;
        ret += go(mask | (1<<i), (mod*10 + v[i])%MOD);
      }
    return memo[mod][mask] = ret;
  }

  static class FastIO extends PrintWriter {
    BufferedReader br;
    StringTokenizer st;

    public FastIO() {
      this(System.in, System.out);
    }

    public FastIO(InputStream in, OutputStream out) {
      super(new BufferedWriter(new OutputStreamWriter(out)));
      br = new BufferedReader(new InputStreamReader(in));
      scanLine();
    }

    public void scanLine() {
      try {
        st = new StringTokenizer(br.readLine().trim());
      } catch (Exception e) {
        throw new RuntimeException(e.getMessage());
      }
    }

    public int numTokens() {
      if (!st.hasMoreTokens()) {
        scanLine();
        return numTokens();
      }
      return st.countTokens();
    }

    public String next() {
      if (!st.hasMoreTokens()) {
        scanLine();
        return next();
      }
      return st.nextToken();
    }

    public double nextDouble() {
      return Double.parseDouble(next());
    }

    public long nextLong() {
      return Long.parseLong(next());
    }

    public int nextInt() {
      return Integer.parseInt(next());
    }
  }
}

import java.io.InputStreamReader;
import java.io.IOException;
import java.util.InputMismatchException;
import java.io.PrintStream;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Nipuna Samarasekara
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		FastScanner in = new FastScanner(inputStream);
		FastPrinter out = new FastPrinter(outputStream);
		TaskD solver = new TaskD();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskD {
   /////////////////////////////////////////////////////////////
    public void solve(int testNumber, FastScanner in, FastPrinter out) {
    long n=in.nextLong();
        int m=in.nextInt();
        String S=""+n;
        int len=S.length();
     long[][] dp= new long[(1<<len)+1][m];
      dp[0][0]=1;
      int[]  pow2= new int[30];
        pow2[0]=1;
        for (int i = 1; i < 30; i++) {
            pow2[i]=2*pow2[i-1];
        }
     long[] pow10= new long[30];
        pow10[0]=1;
        for (int i = 1; i < 30; i++) {
            pow10[i]=(pow10[i-1]*10)%m;
        }
        for (int i = 0; i < len; i++) {
            int cur=(int)S.charAt(i)-(int)'0';
            for (int j = 0; j <= (1<<len) ; j++) {
//                int[] dd=new int[len];
//                for (int l = 0; l < len; l++) {
//
//                    if((j&pow2[l])>0)
//                       dd[l]=1 ;
//                }

                if(Integer.bitCount(j)==i)
                for (int k = 0; k < m; k++) {
                   if(dp[j][k]!=0){
                       for (int l = 0; l < len; l++) {
                         if(cur==0&&l==0)continue;
                           if((j&pow2[l])==0) {
                            int newj=(j|pow2[l]),newk= (int)((k+pow10[len-1-l]*cur));
                               while(newk>=m)newk-=m;
                            dp[newj][newk]+=dp[j][k];

                           }
                       }

                   }

                }
            }
        }

    long ans=  dp[(1<<len)-1][0];
      //  System.out.println(ans);
        int[] aa= new int[10];
        for (int i = 0; i < len; i++) {
            aa[(int)S.charAt(i)-(int)'0']++;
        }
      long[] fact= new long[20];
        fact[0]=1;
        for (int i = 1; i < 20; i++) {
            fact[i]=i*fact[i-1];
        }
        for (int i = 0; i < 10; i++) {
            if(aa[i]>1)ans/=fact[aa[i]];
        }
     //   deb(dp[31]);
        out.println(ans);
      //  deb(dp);
    }
}

class FastScanner extends BufferedReader {

    public FastScanner(InputStream is) {
        super(new InputStreamReader(is));
    }

    public int read() {
        try {
            int ret = super.read();
//            if (isEOF && ret < 0) {
//                throw new InputMismatchException();
//            }
//            isEOF = ret == -1;
            return ret;
        } catch (IOException e) {
            throw new InputMismatchException();
        }
    }

    public String next() {
        StringBuilder sb = new StringBuilder();
        int c = read();
        while (isWhiteSpace(c)) {
            c = read();
        }
        if (c < 0) {
            return null;
        }
        while (c >= 0 && !isWhiteSpace(c)) {
            sb.appendCodePoint(c);
            c = read();
        }
        return sb.toString();
    }

    static boolean isWhiteSpace(int c) {
        return c >= 0 && c <= 32;
    }

    public int nextInt() {
        int c = read();
        while (isWhiteSpace(c)) {
            c = read();
        }
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        int ret = 0;
        while (c >= 0 && !isWhiteSpace(c)) {
            if (c < '0' || c > '9') {
                throw new NumberFormatException("digit expected " + (char) c
                        + " found");
            }
            ret = ret * 10 + c - '0';
            c = read();
        }
        return ret * sgn;
    }

    public long nextLong() {
        return Long.parseLong(next());
    }

    public String readLine() {
        try {
            return super.readLine();
        } catch (IOException e) {
            return null;
        }
    }

    }

class FastPrinter extends PrintWriter {

    public FastPrinter(OutputStream out) {
        super(out);
    }

    public FastPrinter(Writer out) {
        super(out);
    }

}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Abood2C {
	static int N;
	static long memo[][];
	static int MOD;
	static String s;
	static long solve(int i, int m) {

		if(i == 0 && m == 0)
			return 1;
		if(i == 0)
			return 0;
		if(memo[i][m] != -1)
			return memo[i][m];

		long ans = 0;
		int p = 1;
		int c = 0;
		for (int j = 0; j < N; j++) {
			if((i & (1 << j)) == 0)
				c++;
		}
		for (int j = 0; j < c; j++) {
			p *= 10;
			p %= MOD;
		}
		for (int j = 0; j < N; j++) {
			if((i & (1 << j)) == 0 || s.charAt(j) == '0' && (i ^ (1 << j)) == 0)
				continue;
			boolean v = false;
			for (int j2 = 0; j2 < j; j2++)
				if((i & (1 << j2)) != 0 && s.charAt(j) == s.charAt(j2)) {
					v = true;
					continue;
				}

			if(v)
				continue;

			ans += solve((i ^ (1 << j)), ((s.charAt(j) - '0') * p + m) % MOD);
		}
		return memo[i][m] = ans;
	}

	public static void main(String[] args) throws Exception{
		Scanner sc = new Scanner(System.in);
		PrintWriter out = new PrintWriter(System.out);

		s = sc.next();
		N = s.length();
		MOD = sc.nextInt();

		memo = new long [(1 << N)][MOD + 1];
		for (int i = 0; i < memo.length; i++)

			Arrays.fill(memo[i], -1);

		out.println(solve(memo.length - 1, 0));

		out.flush();
		out.close();
	}

	static class Scanner
	{
		StringTokenizer st;
		BufferedReader br;

		public Scanner(InputStream System){	br = new BufferedReader(new InputStreamReader(System));}
		public String next() throws IOException
		{
			while (st == null || !st.hasMoreTokens())
				st = new StringTokenizer(br.readLine());
			return st.nextToken();
		}
		public String nextLine()throws IOException{return br.readLine();}
		public int nextInt() throws IOException {return Integer.parseInt(next());}
		public double nextDouble() throws IOException {return Double.parseDouble(next());}
		public char nextChar()throws IOException{return next().charAt(0);}
		public Long nextLong()throws IOException{return Long.parseLong(next());}
		public boolean ready() throws IOException{return br.ready();}
		public void waitForInput(){for(long i = 0; i < 3e9; i++);}
	}
}

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.StringTokenizer;

public class RomanAndNumbers {
    static char[] arr;
    static int mod;
    static int[] pow;
    static Long[][] dp = new Long[1 << 18][101];

    static long go(int mask, int m, int bits) {
        if (bits == arr.length)
            if (m == 0)
                return 1;
            else
                return 0;
        if (dp[mask][m] != null)
            return dp[mask][m];
        long res = 0;
        int digits = 0;
        for (int j = 0; j < arr.length; j++) {
            if ((mask & (1 << j)) == 0) {
                if (mask == 0 && arr[j] == '0')
                    continue;
                int d = arr[j] - '0';
                if ((digits & (1 << d)) == 0) {
                    res += go(mask | (1 << j), (m + pow[arr.length - 1 - bits] * d) % mod, bits + 1);
                    digits |= (1 << d);
                }
            }
        }
        return dp[mask][m] = res;
    }

    public static void main(String[] args) throws Exception {
        InputReader r = new InputReader(System.in);
        PrintWriter out = new PrintWriter(System.out);
        arr = r.next().toCharArray();
        mod = r.nextInt();
        pow = new int[20];
        pow[0] = 1;
        for (int i = 1; i < pow.length; i++) {
            pow[i] = 10 * pow[i - 1];
            pow[i] %= mod;
        }
        out.println(go(0, 0, 0));
        out.close();
    }

    static class InputReader {
        private BufferedReader reader;
        private StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream));
            tokenizer = null;
        }

        public InputReader(FileReader stream) {
            reader = new BufferedReader(stream);
            tokenizer = null;
        }

        public String nextLine() {
            try {
                return reader.readLine();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return null;
            }
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

        public long nextLong() {
            return Long.parseLong(next());
        }
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class D {
	public static void main(String[] args) {
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			int tc = 0;
			while (true) {
				String line = br.readLine();
				if (line == null) break;
				System.err.println("--------------TEST CASE " + ++tc + "---------------");
				System.err.println("INPUT");
				System.err.println(line);

				String[] s = line.split(" ");
				char[] n = s[0].toCharArray();
				int m = Integer.parseInt(s[1]);

				long t = System.currentTimeMillis();
				System.err.println("\nOUTPUT");
				System.out.println(new D().solve(n, m));
				t = System.currentTimeMillis() - t;
				System.err.println("\nT=" + t);
			}
		} catch (IOException io) {
			io.printStackTrace();
		}
	}

	private int[] n;
	private int m, all;
	private long[] mlt;
	private long[][] ways;

	private long solve(char[] pn, int m) {
		all = (1<<pn.length)-1;
		ways = new long[m+1][all+1];
		for (int i = 0; i < ways.length; i++) {
			Arrays.fill(ways[i],-1);
		}
		mlt = new long[pn.length];
		mlt[mlt.length-1] = 1;
		for (int i = mlt.length-2; i >=0; i--) {
			mlt[i]=10*mlt[i+1];
		}
		n = new int[pn.length];
		for (int i = 0; i < n.length; i++) {
			n[i] = pn[i]-'0';
		}
		Arrays.sort(n);
		this.m = m;
		return go(0,0,0);
	}

	long go(int mask, int rem, int size) {
		if (size == n.length) return rem==0?1:0;
		if (ways[rem][mask]>=0) return ways[rem][mask];
		long mult = mlt[size];
		int used = 0;
		long ret = 0;
		for (int i = 0; i < n.length; i++) {
			int curr = 1<<i;
			if ((mask&curr)!=0) continue;
			int v = n[i];
			if (mask == 0 && v==0) continue;
			int digit = 1<<v;
			if ((used&digit)!=0) continue;
			used |= digit;
			ret += go(mask|curr, (int)((rem+v*mult)%m), size+1);
		}
		return ways[rem][mask] = ret;
	}
}

import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;

public class D {

	static Scanner sc = new Scanner(System.in);
	static PrintWriter out = new PrintWriter(System.out);

	static void exit() {
		sc.close();
		out.close();
		System.exit(0);
	}
	static int [] digits;
	static int m;
	public static void main(String[] args) {
		char [] n = sc.next().toCharArray();
		digits = new int [n.length];
		for(int i = 0; i < n.length; i++) digits[i] = n[i] - '0';
		m = sc.nextInt();
		int mask = (1 << digits.length) - 1;
		dp = new long [mask+1][m];
		for(int i = 0; i < dp.length; i++) Arrays.fill(dp[i], -1);

		out.println(dp(mask, 0));
		exit();
	}
	static long dp [][];
	static long dp(int mask, int re) {
		if(dp[mask][re] > -1) return dp[mask][re];
		if(mask == 0) {
			if(re == 0) {
				dp[mask][re] = 1;
			} else {
				dp[mask][re] = 0;
			}
			return dp[mask][re];
		}
		if(all_zero_digits(mask)) {
			dp[mask][re] = 0;
			return dp[mask][re];
		}
		boolean visited [] = new boolean [10];
		Arrays.fill(visited, false);
		Arrays.fill(dp[mask], 0);
		for(int i = 0; i < digits.length; i++) {
			if((mask & (1<<i)) > 0) {
				if(visited[digits[i]]) continue;
				visited[digits[i]] = true;
				int pre_mask = mask - (1<<i);
				for(int j = 0; j < m; j++) {
					dp[mask][ (j*10 + digits[i]) % m] += dp(pre_mask, j);
				}
			}
		}
		return dp[mask][re];
	}
	static boolean all_zero_digits(int mask) {
		for(int i = 0; i < digits.length; i++) {
			if((mask & (1<<i)) > 0) {
				if(digits[i] > 0) return false;
			}
		}
		return true;
	}
}

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

/**
 * Created by chinh on 7/19/14.
 */
public class R235D2D {
    static long factorial(int x){
        long ret = 1;
        for(int i=2; i<=x; i++) ret*=i;
        return ret;
    }
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        char[] s = st.nextToken().toCharArray();
        int n = s.length;
        int m = Integer.parseInt(st.nextToken());
        long[][] dp = new long[1<<n][m];
        dp[0][0]=1;
        for(int i=1; i<(1<<n); i++){
            for(int p=0; p<n; p++){
                if((i&(1<<p))>0){
                    int j = i ^ (1<<p);
                    if(j==0 && s[p]=='0') continue;
                    for(int r=0; r<m; r++){
                        dp[i][(r*10+s[p]-'0')%m] += dp[j][r];
                    }
                }
            }
        }
        int[] count = new int[10];
        for(int i=0; i<n; i++) count[s[i]-'0']++;
        long ret = dp[(1<<n)-1][0];
        for(int i=0; i<10; i++) ret/=factorial(count[i]);
        System.out.println(ret);
    }

}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.concurrent.PriorityBlockingQueue;

public class aa {

	public static class node implements Comparable<node> {
		int x;
		int y;

		node(int x, int y) {
			this.x = x;
			this.y = y;
		}

		@Override
		public int compareTo(node o) {
			if (o.x < x)
				return 1;
			else if (o.x > x)
				return -1;
			else if (o.y < y)
				return 1;
			else
				return -1;
		}
	}

	public static int mod;
	public static String num;

	public static long dp[][];
	public static int a[];
	public static int n;

	public static long getFact() {
		int a[] = new int[10];
		for (int i = 0; i < num.length(); i++) {
			a[num.charAt(i) - 48]++;
		}
		long fact = 1;
		for (int i = 0; i < 10; i++) {
			if (a[i] != 0)
				fact *= fact(a[i]);
		}
		return fact;
	}

	public static long fact(int n) {
		long ans = 1;
		for (int i = 1; i <= n; i++) {
			ans *= i;
		}
		return ans;
	}

	public static long f;

	public static long solve(int mask, int number, int count, int last) {

		if (mask == (1 << n) - 1) {
			if (number == 0)
				return 1;
			return 0;

		}
		if (dp[mask][number] != -1)
			return dp[mask][number];
		long a1 = 0;
		for (int i = 0; i < n; i++) {

			// if (a[i] != last) {
			if (count != 0 || a[i] != 0) {
				if(i>0&&(mask&(1<<(i-1)))==0&&a[i-1]==a[i])
					continue;
				if ((mask & (1 << i)) == 0) {
					a1 += solve(mask | (1 << i), (number * 10 + a[i]) % mod,
							count + 1, a[i]);

				}
			}
			// }

		}
		dp[mask][number] = a1;
		return a1;

	}

	public static void main(String[] args) throws IOException {

		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
		StringBuilder q = new StringBuilder();
		String y[] = in.readLine().trim().split(" ");
		num = y[0];
		mod = Integer.parseInt(y[1]);
		n = num.length();
		a = new int[n];
		for (int i = 0; i < n; i++) {
			a[i] = num.charAt(i) - 48;
		}
		Arrays.sort(a);

		dp = new long[1 << n + 1][mod];
		for (int i = 0; i < (1 << n + 1); i++) {
			for (int j = 0; j < mod; j++) {
				dp[i][j] = -1;
			}
		}
		f = getFact();

		// System.out.println(t);
		// System.out.println(f);
		out.println((long) solve(0, 0, 0, 0));

		out.print(q);
		out.close();

	}
}

import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.HashSet;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		PrintWriter out = new PrintWriter(outputStream);
		TaskD solver = new TaskD();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskD {
    long dp[][];
    char no[];
    int m;
    int len;
    public void solve(int testNumber, InputReader in, PrintWriter out) {
        no = (in.readLong() + "").toCharArray();
        len = no.length;
        m = in.readInt();
        dp = new long[1 << 18][100];
        for (long[] a : dp) Arrays.fill(a, -1);
        out.println(go(0, 0));
    }
    long go(int mask, int mod) {
        if (mask == (1 << len) - 1){
            if (mod == 0) return 1;
            return 0;
        }
        HashSet<Character> hs = new HashSet<Character>();
        if (dp[mask][mod] != -1) return dp[mask][mod];
        long ans = 0;
        for (int i = 0; i < len; i++) {
            if (((mask >> i) & 1) != 0) continue;
            if (mask == 0 && no[i] == '0') continue;
            if (hs.contains(no[i])) continue;
            hs.add(no[i]);
            ans += go(mask | (1 << i), ((mod * 10) + no[i] - '0') % m);
        }
        return dp[mask][mod] = ans;
    }
}

class InputReader {

        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream) {
                this.stream = stream;
        }

        public int read() {
                if (numChars == -1)
                        throw new InputMismatchException();
                if (curChar >= numChars) {
                        curChar = 0;
                        try {
                                numChars = stream.read(buf);
                        } catch (IOException e) {
                                throw new InputMismatchException();
                        }
                        if (numChars <= 0)
                                return -1;
                }
                return buf[curChar++];
        }

        public int readInt() {
                int c = read();
                while (isSpaceChar(c))
                        c = read();
                int sgn = 1;
                if (c == '-') {
                        sgn = -1;
                        c = read();
                }
                int res = 0;
                do {
                        if (c < '0' || c > '9')
                                throw new InputMismatchException();
                        res *= 10;
                        res += c - '0';
                        c = read();
                } while (!isSpaceChar(c));
                return res * sgn;
        }

        public long readLong() {
                int c = read();
                while (isSpaceChar(c))
                        c = read();
                int sgn = 1;
                if (c == '-') {
                        sgn = -1;
                        c = read();
                }
                long res = 0;
                do {
                        if (c < '0' || c > '9')
                                throw new InputMismatchException();
                        res *= 10;
                        res += c - '0';
                        c = read();
                } while (!isSpaceChar(c));
                return res * sgn;
        }

        public boolean isSpaceChar(int c) {
                if (filter != null)
                        return filter.isSpaceChar(c);
                return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
                return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
                public boolean isSpaceChar(int ch);
        }
}

//Author: net12k44
import java.io.*;
import java.util.*;
//public
class Main{//}

static PrintWriter out;

boolean check(int state, int a[] , int n){
	boolean d[] = new boolean[10];
	for(int i = 0; i < n; ++i)
	 if ( ( state & (1 << i) ) == 0 ) d[ a[i] ] = true; else
	 if ( d[a[i]] == true ) return false;

	return true;
}

private void solve() {
	long number = in.nextLong();
	int m = in.nextInt();
	int a[] = new int[20] , n = 0;

	while (number > 0){
		a[n++] = (int)( number%10 );
		number /=10;
	}
	Arrays.sort(a,0,n);

	long f[][] = new long[1 << n][m];
	for(int i = 0; i < n; ++i)
	  if (a[i] != 0) f[1<<i][a[i]%m] = 1;

	for(int state = 1; state+1 < (1 << n); ++state)
		if (check(state , a , n) )
			for(int i = 0; i < n; ++i)
				if ( ( state & (1 << i) ) == 0 ){
					int next = state | (1 << i);
					for(int mod = 0; mod < m; ++mod)
					f[next][ (mod*10 + a[i]) % m ] += f[state][mod];
				}

	out.println( f[ (1 << n) - 1 ][0] );
}

public static void main (String[] args) throws java.lang.Exception {
    long startTime = System.currentTimeMillis();

    out = new PrintWriter(System.out);
    new Main().solve();
    //out.println((String.format("%.2f",(double)(System.currentTimeMillis()-startTime)/1000)));
    out.close();
}

static class in {
    static BufferedReader reader = new BufferedReader( new InputStreamReader(System.in) ) ;
    static StringTokenizer tokenizer = new StringTokenizer("");
    static String next() {
        while ( !tokenizer.hasMoreTokens() )
            try { tokenizer = new StringTokenizer( reader.readLine() ); }
            catch (IOException e){
                throw new RuntimeException(e);
            }
        return tokenizer.nextToken();
    }
    static int nextInt() { return Integer.parseInt( next() ); }
    static long nextLong(){ return Long.parseLong( next() ); }
}
//////////////////////////////////////////////////
}//

import java.util.*;
public class D {
	Scanner sc = new Scanner(System.in);
	void doIt() {
		char [] c_n = sc.next().toCharArray();
		int m = sc.nextInt();
		int len = c_n.length;
		int [] n = new int[len];
		int [] dcnt = new int[10];
		long div = 1L;
		for(int i = 0; i < len; i++) {
			n[i]  = (int)(c_n[i] - '0');
			dcnt[n[i]]++;
			div *= (long)dcnt[n[i]];
		}
		long dp[][] = new long[1<<len][m];
		dp[0][0] = 1;
		int [] base = new int[len];
		base[0] = 1;
		for(int i = 1; i < len; i++) base[i] = (base[i-1] * 10) % m;
		for(int mask = 0; mask < (1<<len)-1; mask++) {
			int cnt = Integer.bitCount(mask);
			for(int i = 0; i < len; i++) {
				if((mask & (1<<i)) == 0) { // not used
					int nmask = mask | (1<<i);
					if(n[i] == 0 && nmask == (1<<len)-1) continue;
					for(int v = 0; v < m; v++) {
						int nv = (v + n[i] * base[cnt]) % m;
						dp[nmask][nv] += dp[mask][v];
						//System.out.println(v + " " + mask + "=>" + nmask + " " + nv + " " + dp[nmask][nv]);
					}

				}
			}
		}
//		for(int mask = 0; mask < (1<<len); mask++) {
//			System.out.println(mask + "  " + Arrays.toString(dp[mask]));
//		}
//		System.out.println(Arrays.toString(dp[(1<<len)-1]));
//		System.out.println(div);
		System.out.println(dp[(1<<len)-1][0] / div);
	}
	public static void main(String[] args) {
		new D().doIt();

	}

}

import java.io.*;
import java.util.*;

public class Main {
	public static void main(String[] args) throws Exception {

		Scanner in = new Scanner(System.in);
		String n = in.next();
		int m = in.nextInt();

		byte[] nums = new byte[10];
		for(char ch: n.toCharArray()) {
			++nums[Character.digit(ch, 10)];
		}
		int total = 1;
		for(byte num: nums) {
			total *= num + 1;
		}

		long[][] dp = new long[total][m];
		dp[0][0] = 1;

		for(int i = 1; i < total; ++i) {
			for(int j = 0; j < m; ++j) {
				int d = 1;
				int numCount = 0;
				for(int k = 0; k < 10; ++k) {
					if(nums[k] != 0) {
						numCount += i / d % (nums[k] + 1);
						d *= nums[k] + 1;
					}
				}
				d = 1;
				long level = Fun.power(10, numCount - 1);
				for(int k = 0; k < 10; ++k) {
					if(nums[k] != 0) {
						int count = i / d % (nums[k] + 1);
						if(count != 0) {
							int currem = (int) (k * level % m);
							dp[i][j] += dp[i / (d * (nums[k] + 1)) * (d * (nums[k] + 1)) + (count - 1) * d + i % d][(j + m - currem) % m];
						}
						d *= nums[k] + 1;
					}
				}
			}
		}

		if(nums[0] == 0) {
			System.out.println(dp[total - 1][0]);
		} else {
			System.out.println(dp[total - 1][0] - dp[total - 1 - 1][0]);
		}
	}

}

// ///////////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////

class Fun {

	public static long power(long n, long e) {
		long result = 1;
		for(long i = 0; i < e; ++i) {
			result *= n;
		}
		return result;
	}

	public static int[] nextInts(Scanner in, int count) {
		int[] result = new int[count];
		for (int i = 0; i < count; ++i) {
			result[i] = in.nextInt();
		}
		return result;
	}

	public static boolean isPrime(int n) {
		boolean result = true;
		for(int i = 2; i * i <= n; ++i) {
			if(n % i == 0) {
				result = false;
				break;
			}
		}
		return result;
	}

	public static long gcd(long a, long b) {
		if (b == 0)
			return a;
		return gcd(b, a % b);
	}

	public static int gcd(int a, int b) {
		if (b == 0)
			return a;
		return gcd(b, a % b);
	}

	public static long lcm(long a, long b) {
		return a / gcd(a, b) * b;
	}

	public static int[][] transpose(int[][] mat) {
		int r = mat.length;
		int c = mat[0].length;
		int[][] result = new int[c][r];
		for (int i = 0; i < c; ++i)
			for (int j = 0; j < r; ++j)
				result[i][j] = mat[j][i];
		return result;
	}

	public static String repeatString(String s, long count) {
		StringBuilder sb = new StringBuilder();
		for (long i = 0; i < count; ++i) {
			sb.append(s);
		}
		return sb.toString();
	}
}

class Treap<K extends Comparable<? super K>, V> {

	Treap() {
		nullNode = new TreapNode<K, V>();
		nullNode.left = nullNode.right = nullNode;
		nullNode.priority = Integer.MAX_VALUE;
		rootNode = nullNode;
	}

	public V put(K key, V value) {
		PutResult<K, V> putResult = putHelp(rootNode, key, value);
		rootNode = putResult.newNode;
		return putResult.originalValue;
	}

	public V get(K key) {
		TreapNode<K, V> currentNode = rootNode;
		while(currentNode != nullNode && currentNode.key.compareTo(key) != 0) {
			if(key.compareTo(currentNode.key) < 0) {
				currentNode = currentNode.left;
			} else {
				currentNode = currentNode.right;
			}
		}

		if(currentNode == nullNode) {
			return null;
		} else {
			return currentNode.value;
		}
	}

	public V remove(K key) {
		V result = get(key);
		if(result != null) {
			rootNode = removeHelp(rootNode, key);
		}
		return result;
	}

	public K select(int rank) {
		if(rank >= size() || rank < 0) {
			return null;
		}
		TreapNode<K, V> currentNode = rootNode;
		while(rank != currentNode.left.size) {
			if(rank < currentNode.left.size) {
				currentNode = currentNode.left;
			} else {
				rank -= currentNode.left.size + 1;
				currentNode = currentNode.right;
			}
		}

		return currentNode.key;
	}

	public int rank(K key) {
		if(rootNode == nullNode) {
			return -1;
		}
		int result = rootNode.left.size;
		TreapNode<K, V> currentNode = rootNode;
		while(currentNode != nullNode && currentNode.key.compareTo(key) != 0) {
			if(key.compareTo(currentNode.key) < 0) {
				result -= currentNode.left.right.size + 1;
				currentNode = currentNode.left;
			} else {
				result += currentNode.right.left.size + 1;
				currentNode = currentNode.right;
			}
		}

		if(currentNode == nullNode) {
			return -1;
		} else {
			return result;
		}
	}

	public void clear() {
		rootNode = nullNode;
	}

	public int size() {
		return rootNode.size;
	}

	private static class TreapNode<K, V> {
		public K key;
		public V value;
		public int size;
		public int priority;
		TreapNode<K, V> left, right;
	}

	private static class PutResult<K, V> {
		public TreapNode<K, V> newNode;
		public V originalValue;
	}

	private PutResult<K, V> putHelp(TreapNode<K, V> node, K key, V value) {
		if(node == nullNode) {
			PutResult<K, V> result = new PutResult<K, V>();
			result.newNode = new TreapNode<K, V>();
			result.newNode.key = key;
			result.newNode.value = value;
			result.newNode.size = 1;
			result.newNode.priority = randomPriority.nextInt(Integer.MAX_VALUE);
			result.newNode.left = result.newNode.right = nullNode;
			return result;
		} else if(key.compareTo(node.key) == 0) {
			PutResult<K, V> result = new PutResult<K, V>();
			result.originalValue = node.value;
			node.value = value;
			result.newNode = node;
			return result;
		} else if(key.compareTo(node.key) < 0) {
			PutResult<K, V> result = putHelp(node.left, key, value);
			node.left = result.newNode;
			if(result.originalValue == null) {
				++node.size;
				if(node.left.priority < node.priority) {
					node = rightRotate(node);
				}
			}
			result.newNode = node;
			return result;
		} else {
			PutResult<K, V> result = putHelp(node.right, key, value);
			node.right = result.newNode;
			if(result.originalValue == null) {
				++node.size;
				if(node.right.priority < node.priority) {
					node = leftRotate(node);
				}
			}
			result.newNode = node;
			return result;
		}
	}

	private TreapNode<K, V> removeHelp(TreapNode<K, V> node, K key) {
		if(key.compareTo(node.key) == 0) {
			node = removeHelp2(node);
		} else if(key.compareTo(node.key) < 0) {
			--node.size;
			node.left = removeHelp(node.left, key);
		} else {
			--node.size;
			node.right = removeHelp(node.right, key);
		}
		return node;
	}

	private TreapNode<K, V> removeHelp2(TreapNode<K, V> node) {
		if(node.left == nullNode && node.right == nullNode) {
			return nullNode;
		}

		if(node.left.priority < node.right.priority) {
			node = rightRotate(node);
			--node.size;
			node.right = removeHelp2(node.right);
		} else {
			node = leftRotate(node);
			--node.size;
			node.left = removeHelp2(node.left);
		}
		return node;
	}

	private TreapNode<K, V> leftRotate(TreapNode<K, V> node) {
		TreapNode<K, V> result = node.right;
		node.right = result.left;
		result.left = node;
		result.size = node.size;
		node.size -= 1 + result.right.size;
		return result;
	}

	private TreapNode<K, V> rightRotate(TreapNode<K, V> node) {
		TreapNode<K, V> result = node.left;
		node.left = result.right;
		result.right = node;
		result.size = node.size;
		node.size -= 1 + result.left.size;
		return result;
	}

	private TreapNode<K, V> nullNode;
	private TreapNode<K, V> rootNode;
	private Random randomPriority = new Random();
}

import java.io.*;
import java.util.*;

public class Main {
	public static void main(String[] args) throws Exception {

		Scanner in = new Scanner(System.in);
		String n = in.next();
		int m = in.nextInt();

		byte[] nums = new byte[10];
		for(char ch: n.toCharArray()) {
			++nums[Character.digit(ch, 10)];
		}
		int total = 1;
		for(byte num: nums) {
			total *= num + 1;
		}

		long[][] dp = new long[total][m];
		dp[0][0] = 1;

		for(int i = 1; i < total; ++i) {
			int d = 1;
			int numCount = 0;
			for(int k = 0; k < 10; ++k) {
				if(nums[k] != 0) {
					numCount += i / d % (nums[k] + 1);
					d *= nums[k] + 1;
				}
			}
			long level = Fun.power(10, numCount - 1);

			for(int j = 0; j < m; ++j) {
				d = 1;
				for(int k = 0; k < 10; ++k) {
					if(nums[k] != 0) {
						int count = i / d % (nums[k] + 1);
						if(count != 0) {
							int currem = (int) (k * level % m);
							int level2 = (d * (nums[k] + 1));
							dp[i][j] += dp[i / level2 * level2 + (count - 1) * d + i % d][(j + m - currem) % m];
						}
						d *= nums[k] + 1;
					}
				}
			}
		}

		if(nums[0] == 0) {
			System.out.println(dp[total - 1][0]);
		} else {
			System.out.println(dp[total - 1][0] - dp[total - 1 - 1][0]);
		}
	}

}

// ///////////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////

class Fun {

	public static long power(long n, long e) {
		long result = 1;
		for(long i = 0; i < e; ++i) {
			result *= n;
		}
		return result;
	}

	public static int[] nextInts(Scanner in, int count) {
		int[] result = new int[count];
		for (int i = 0; i < count; ++i) {
			result[i] = in.nextInt();
		}
		return result;
	}

	public static boolean isPrime(int n) {
		boolean result = true;
		for(int i = 2; i * i <= n; ++i) {
			if(n % i == 0) {
				result = false;
				break;
			}
		}
		return result;
	}

	public static long gcd(long a, long b) {
		if (b == 0)
			return a;
		return gcd(b, a % b);
	}

	public static int gcd(int a, int b) {
		if (b == 0)
			return a;
		return gcd(b, a % b);
	}

	public static long lcm(long a, long b) {
		return a / gcd(a, b) * b;
	}

	public static int[][] transpose(int[][] mat) {
		int r = mat.length;
		int c = mat[0].length;
		int[][] result = new int[c][r];
		for (int i = 0; i < c; ++i)
			for (int j = 0; j < r; ++j)
				result[i][j] = mat[j][i];
		return result;
	}

	public static String repeatString(String s, long count) {
		StringBuilder sb = new StringBuilder();
		for (long i = 0; i < count; ++i) {
			sb.append(s);
		}
		return sb.toString();
	}
}

class Treap<K extends Comparable<? super K>, V> {

	Treap() {
		nullNode = new TreapNode<K, V>();
		nullNode.left = nullNode.right = nullNode;
		nullNode.priority = Integer.MAX_VALUE;
		rootNode = nullNode;
	}

	public V put(K key, V value) {
		PutResult<K, V> putResult = putHelp(rootNode, key, value);
		rootNode = putResult.newNode;
		return putResult.originalValue;
	}

	public V get(K key) {
		TreapNode<K, V> currentNode = rootNode;
		while(currentNode != nullNode && currentNode.key.compareTo(key) != 0) {
			if(key.compareTo(currentNode.key) < 0) {
				currentNode = currentNode.left;
			} else {
				currentNode = currentNode.right;
			}
		}

		if(currentNode == nullNode) {
			return null;
		} else {
			return currentNode.value;
		}
	}

	public V remove(K key) {
		V result = get(key);
		if(result != null) {
			rootNode = removeHelp(rootNode, key);
		}
		return result;
	}

	public K select(int rank) {
		if(rank >= size() || rank < 0) {
			return null;
		}
		TreapNode<K, V> currentNode = rootNode;
		while(rank != currentNode.left.size) {
			if(rank < currentNode.left.size) {
				currentNode = currentNode.left;
			} else {
				rank -= currentNode.left.size + 1;
				currentNode = currentNode.right;
			}
		}

		return currentNode.key;
	}

	public int rank(K key) {
		if(rootNode == nullNode) {
			return -1;
		}
		int result = rootNode.left.size;
		TreapNode<K, V> currentNode = rootNode;
		while(currentNode != nullNode && currentNode.key.compareTo(key) != 0) {
			if(key.compareTo(currentNode.key) < 0) {
				result -= currentNode.left.right.size + 1;
				currentNode = currentNode.left;
			} else {
				result += currentNode.right.left.size + 1;
				currentNode = currentNode.right;
			}
		}

		if(currentNode == nullNode) {
			return -1;
		} else {
			return result;
		}
	}

	public void clear() {
		rootNode = nullNode;
	}

	public int size() {
		return rootNode.size;
	}

	private static class TreapNode<K, V> {
		public K key;
		public V value;
		public int size;
		public int priority;
		TreapNode<K, V> left, right;
	}

	private static class PutResult<K, V> {
		public TreapNode<K, V> newNode;
		public V originalValue;
	}

	private PutResult<K, V> putHelp(TreapNode<K, V> node, K key, V value) {
		if(node == nullNode) {
			PutResult<K, V> result = new PutResult<K, V>();
			result.newNode = new TreapNode<K, V>();
			result.newNode.key = key;
			result.newNode.value = value;
			result.newNode.size = 1;
			result.newNode.priority = randomPriority.nextInt(Integer.MAX_VALUE);
			result.newNode.left = result.newNode.right = nullNode;
			return result;
		} else if(key.compareTo(node.key) == 0) {
			PutResult<K, V> result = new PutResult<K, V>();
			result.originalValue = node.value;
			node.value = value;
			result.newNode = node;
			return result;
		} else if(key.compareTo(node.key) < 0) {
			PutResult<K, V> result = putHelp(node.left, key, value);
			node.left = result.newNode;
			if(result.originalValue == null) {
				++node.size;
				if(node.left.priority < node.priority) {
					node = rightRotate(node);
				}
			}
			result.newNode = node;
			return result;
		} else {
			PutResult<K, V> result = putHelp(node.right, key, value);
			node.right = result.newNode;
			if(result.originalValue == null) {
				++node.size;
				if(node.right.priority < node.priority) {
					node = leftRotate(node);
				}
			}
			result.newNode = node;
			return result;
		}
	}

	private TreapNode<K, V> removeHelp(TreapNode<K, V> node, K key) {
		if(key.compareTo(node.key) == 0) {
			node = removeHelp2(node);
		} else if(key.compareTo(node.key) < 0) {
			--node.size;
			node.left = removeHelp(node.left, key);
		} else {
			--node.size;
			node.right = removeHelp(node.right, key);
		}
		return node;
	}

	private TreapNode<K, V> removeHelp2(TreapNode<K, V> node) {
		if(node.left == nullNode && node.right == nullNode) {
			return nullNode;
		}

		if(node.left.priority < node.right.priority) {
			node = rightRotate(node);
			--node.size;
			node.right = removeHelp2(node.right);
		} else {
			node = leftRotate(node);
			--node.size;
			node.left = removeHelp2(node.left);
		}
		return node;
	}

	private TreapNode<K, V> leftRotate(TreapNode<K, V> node) {
		TreapNode<K, V> result = node.right;
		node.right = result.left;
		result.left = node;
		result.size = node.size;
		node.size -= 1 + result.right.size;
		return result;
	}

	private TreapNode<K, V> rightRotate(TreapNode<K, V> node) {
		TreapNode<K, V> result = node.left;
		node.left = result.right;
		result.right = node;
		result.size = node.size;
		node.size -= 1 + result.left.size;
		return result;
	}

	private TreapNode<K, V> nullNode;
	private TreapNode<K, V> rootNode;
	private Random randomPriority = new Random();
}

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.SortedSet;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;

public class Main
{
	public void foo()
	{
		MyScanner scan = new MyScanner();
		String s = scan.next();
		int m = scan.nextInt();
		int n = s.length();
		int[] ch = new int[n];
		for(int i = 0;i < n;++i)
		{
			ch[i] = s.charAt(i) - '0';
		}
		long[][] dp = new long[1 << n][m];
		dp[0][0] = 1;
		boolean[] vis = new boolean[10];
		for(int i = 0;i < (1 << n) - 1;++i)
		{
			for(int j = 0;j < m;++j)
			{
				Arrays.fill(vis, false);
				for(int k = 0;k < n;++k)
				{
					if((i & (1 << k)) != 0 || vis[ch[k]] || (0 == i && 0 == ch[k]))
					{
						continue;
					}
					vis[ch[k]] = true;
					int iNext = i | (1 << k);
					int jNext = (10 * j + ch[k]) % m;
					dp[iNext][jNext] += dp[i][j];
				}
			}
		}
		System.out.println(dp[(1 << n) - 1][0]);
	}

	public static void main(String[] args)
	{
		new Main().foo();
	}

	class MyScanner
	{
	    private byte[] buf = new byte[1024];
	    private int curChar;
	    private int numChars;
	    BufferedInputStream bis = new BufferedInputStream(System.in);

	    public int read()
	    {
	        if (-1 == numChars)
	        {
	        	throw new InputMismatchException();
	        }
	        if (curChar >= numChars)
	        {
	            curChar = 0;
	            try
	            {
	                numChars = bis.read(buf);
	            }
	            catch (IOException e)
	            {
	                throw new InputMismatchException();
	            }
	            if (numChars <= 0)
	            {
	            	return -1;
	            }
	        }
	        return buf[curChar++];
	    }

	    public int nextInt()
	    {
	        int c = read();
	        while (isSpaceChar(c))
	        {
	        	c = read();
	        }
	        int sgn = 1;
	        if (c == '-')
	        {
	            sgn = -1;
	            c = read();
	        }
	        int res = 0;
	        do
	        {
	            if (c < '0' || c > '9')
	            {
	            	throw new InputMismatchException();
	            }
	            res *= 10;
	            res += c - '0';
	            c = read();
	        } while (!isSpaceChar(c));
	        return res * sgn;
	    }

	    public long nextLong()
	    {
	    	int c = read();
	    	while (isSpaceChar(c))
	    	{
	    		c = read();
	    	}
	    	int sgn = 1;
	    	if (c == '-')
	    	{
	    		sgn = -1;
	    		c = read();
	    	}
	    	long res = 0;
	    	do
	    	{
	    		if (c < '0' || c > '9')
	    		{
	    			throw new InputMismatchException();
	    		}
	    		res *= 10;
	    		res += c - '0';
	    		c = read();
	    	} while (!isSpaceChar(c));
	    	return res * sgn;
	    }

	    public String next()
	    {
	        int c = read();
	        while (isSpaceChar(c))
	        {
	        	c = read();
	        }
	        StringBuilder res = new StringBuilder();
	        do
	        {
	            res.appendCodePoint(c);
	            c = read();
	        } while (!isSpaceChar(c));
	        return res.toString();
	    }

	    private boolean isSpaceChar(int c)
	    {
	        return ' ' == c || '\n' == c || '\r' == c || '\t' == c || -1 == c;
	    }
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.StringTokenizer;

public class D  {

	static class Scanner{
		BufferedReader br=null;
		StringTokenizer tk=null;
		public Scanner(){
			br=new BufferedReader(new InputStreamReader(System.in));
		}
		public String next() throws IOException{
			while(tk==null || !tk.hasMoreTokens())
				tk=new StringTokenizer(br.readLine());
			return tk.nextToken();
		}
		public int nextInt() throws NumberFormatException, IOException{
			return Integer.valueOf(next());
		}
		public long nextLong() throws NumberFormatException, IOException{
			return Long.valueOf(next());
		}
		public double nextDouble() throws NumberFormatException, IOException{
			return Double.valueOf(next());
		}
	}

	static class State{
		@Override
		public int hashCode() {
			final int prime = 31;
			int result = 1;
			result = prime * result + Arrays.hashCode(a);
			result = prime * result + mod;
			return result;
		}
		@Override
		public boolean equals(Object obj) {
			if (this == obj)
				return true;
			if (obj == null)
				return false;
			if (getClass() != obj.getClass())
				return false;
			State other = (State) obj;
			if (!Arrays.equals(a, other.a))
				return false;
			if (mod != other.mod)
				return false;
			return true;
		}
		int[] a;
		int mod;
		public State(int[] b, int m){
			a = b;
			mod = m;
		}
		int getdigits(){
			int ret = 0;
			for(int i = 0; i < a.length; i++)
				ret += a[i];
			return ret;
		}
	}

	static HashMap<State, Long> dp;
	static int totaldigits;
	static int[] powmod10;
	static long N;
	static int M;

	static long dp(State s){
		if (dp.containsKey(s))
			return dp.get(s);
		int[] array = s.a;
		int mod = s.mod;
		int faltan  = s.getdigits();
		if (faltan == 0){
			return (mod == 0)?1L:0L;
		}
		long ret = 0;
		for(int i = 0; i < array.length; i++){
			if(array[i] == 0)
				continue;
			if (faltan == totaldigits && i == 0)
				continue;
			int nmod = (powmod10[faltan - 1] * i) % M;
			nmod = (mod + nmod) % M;
			array[i]--;
			State ns = new State(array, nmod);
			ret += dp(ns);
			array[i]++;
		}
		dp.put(s, ret);
		return ret;
	}

	public static void main(String args[]) throws NumberFormatException, IOException{
		Scanner sc = new Scanner();
		N = sc.nextLong();
		M = sc.nextInt();
		totaldigits = (N+"").length();
		powmod10 = new int[20];
		powmod10[0] = 1 % M;
		for(int i = 1; i < 20; i++)
			powmod10[i] = (powmod10[i - 1] * 10) % M;
		int[] array = new int[10];
		Arrays.fill(array, 0);
		String cad = N + "";
		for(int i = 0; i < cad.length(); i++)
			array[cad.charAt(i) - '0']++;
		State s = new State(array, 0);
		dp = new HashMap<State, Long>();
		System.out.println(dp(s));
	}

}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;

public class _D {
    static long dp[][],ten[];
    static int len,arr[],m;
    static long solve(int index, int mod,int mask){
        if(index == len){
            if(mod%m==0){
                return 1;
            }
            return 0;
        }
        else if(dp[mod][mask]!=-1){
            return dp[mod][mask];
        }
        else {
            long way =0;
            int red[] = new int [10];
            for(int i= 0;i<len;i++){
                if((mask&(1<<i))==0){
                    if((index==0&&arr[i]==0)||red[arr[i]]==1)
                        continue;
                    red[arr[i]] = 1;
                    way+=solve(index+1, (int) (mod+(arr[i]*(ten[len-index-1]%m))%m)%m, mask|(1<<i));
                }
            }
            return dp[mod][mask]=  way;
        }
    }
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(System.out);
        StringTokenizer st = new StringTokenizer(in.readLine());
        long n = Long.parseLong(st.nextToken());
        ten = new long [19];
        ten[0] = 1;
        for(int i=1;i<ten.length;i++)
            ten[i]=ten[i-1]*10;
        m = Integer.parseInt(st.nextToken());
        long temp = n;
        while(temp>0){
            temp/=10;
            len++;
        }
        arr= new int[len];
        int i = 0;
        int digit[] = new int [10];
        while(n>0){
            arr[i] = (int) (n%10);
            digit[arr[i]]++;
            i++;
            n/=10;
        }
        dp = new long [101][1<<18];
        for(i = 0;i<dp.length;i++)
            Arrays.fill(dp[i], -1);
        out.println(solve(0,0, 0));
        in.close();
        out.close();
    }

}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;

public class _D {
    static long dp[][],ten[];
    static int len,arr[],m;
    static long solve(int index, int mod,int mask){
        if(index == len){
            if(mod%m==0){
                return 1;
            }
            return 0;
        }
        else if(dp[mod][mask]!=-1){
            return dp[mod][mask];
        }
        else {
            long way =0;
            int red[] = new int [10];
            for(int i= 0;i<len;i++){
                if((mask&(1<<i))==0){
                    if((index==0&&arr[i]==0)||red[arr[i]]==1)
                        continue;
                    red[arr[i]] = 1;
                    way+=solve(index+1, (int) (mod+(arr[i]*(ten[len-index-1]%m))%m)%m, mask|(1<<i));
                }
            }
            return dp[mod][mask]=  way;
        }
    }
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(System.out);
        long t = System.currentTimeMillis();
        StringTokenizer st = new StringTokenizer(in.readLine());
        long n = Long.parseLong(st.nextToken());
        ten = new long [19];
        ten[0] = 1;
        for(int i=1;i<ten.length;i++)
            ten[i]=ten[i-1]*10;
        m = Integer.parseInt(st.nextToken());
        long temp = n;
        while(temp>0){
            temp/=10;
            len++;
        }
        arr= new int[len];
        int i = 0;
        int digit[] = new int [10];
        while(n>0){
            arr[i] = (int) (n%10);
            digit[arr[i]]++;
            i++;
            n/=10;
        }
        dp = new long [m][1<<len];
        for(i = 0;i<dp.length;i++)
            Arrays.fill(dp[i], -1);
        out.println(solve(0,0, 0));
        in.close();
        out.close();
    }

}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;

public class D {

	static char[] ch;
	static int m;
	static long[][] dp;

	static long solve(int mask, int mod, int len) {
		if (len == ch.length)
			return mod == 0 ? 1L : 0;
		if (dp[mask][mod] != -1)
			return dp[mask][mod];
		long ans = 0;
		for (int i = 0; i < ch.length; i++) {
			if ((mask & (1 << i)) == 0) {
				if (ch[i] == '0' && len == 0)
					continue;
				if (i > 0 && ch[i] == ch[i - 1] && (mask & (1 << (i - 1))) == 0)
					continue;
				ans += solve(mask | (1 << i), (mod * 10 + (ch[i] - '0')) % m,
						len + 1);
			}
		}

		return dp[mask][mod] = ans;
	}

	public static void main(String[] args) throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		out = new PrintWriter(System.out);
		sc = new StringTokenizer("");
		ch = nxtCharArr();
		Arrays.sort(ch);
		m = nxtInt();
		dp = new long[1 << ch.length][m];
		for (long[] a : dp)
			Arrays.fill(a, -1);
		out.println(solve(0, 0, 0));
		br.close();
		out.close();
	}

	static BufferedReader br;
	static StringTokenizer sc;
	static PrintWriter out;

	static String nxtTok() throws IOException {
		while (!sc.hasMoreTokens()) {
			String s = br.readLine();
			if (s == null)
				return null;
			sc = new StringTokenizer(s.trim());
		}
		return sc.nextToken();
	}

	static int nxtInt() throws IOException {
		return Integer.parseInt(nxtTok());
	}

	static long nxtLng() throws IOException {
		return Long.parseLong(nxtTok());
	}

	static double nxtDbl() throws IOException {
		return Double.parseDouble(nxtTok());
	}

	static int[] nxtIntArr(int n) throws IOException {
		int[] a = new int[n];
		for (int i = 0; i < n; i++)
			a[i] = nxtInt();
		return a;
	}

	static long[] nxtLngArr(int n) throws IOException {
		long[] a = new long[n];
		for (int i = 0; i < n; i++)
			a[i] = nxtLng();
		return a;
	}

	static char[] nxtCharArr() throws IOException {
		return nxtTok().toCharArray();
	}
}

import java.io.*;
import java.math.*;
import java.util.*;

public class Main {

    InputReader in;
    PrintWriter out;

    void run(){
        out = new PrintWriter(new OutputStreamWriter(System.out));
        in = new InputReader(System.in);
        solve();
        out.flush();
    }

    public static void main(String[] args){
        new Main().run();
    }

    int[] digits;
    int m;
    long[][] dp;
    int full;

    long divisible(int remainder, int taken) {
        if(taken == full) {
            return (remainder == 0 ? 1 : 0);
        }
        if(dp[taken][remainder] != -1)
            return dp[taken][remainder];
        long res = 0;
        for(int i = 0; i < digits.length; i++) {
            if((taken & (1 << i)) == 0) {
                if(taken == 0 && digits[i] == 0)
                    continue;
                if(i > 0 && digits[i-1] == digits[i] && (taken & (1 << (i-1))) == 0)
                    continue;
                res += divisible((remainder * 10 + digits[i]) % m, taken | (1 << i));
            }
        }
        return dp[taken][remainder] = res;
    }

    void solve() {
        String s = in.ns();
        m = in.ni();
        digits = new int[s.length()];
        for(int i = 0; i < digits.length; i++)
            digits[i] = s.charAt(i) - '0';
        dp = new long[1<<digits.length][101];
        for(long[] x : dp)
            Arrays.fill(x, -1);
        Arrays.sort(digits);
        full = (1 << digits.length) - 1;
        out.println(divisible(0, 0));
    }

    class InputReader {
        private boolean finished = false;
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream) {
                this.stream = stream;
        }

        public int read() {
                if (numChars == -1)
                        throw new InputMismatchException();
                if (curChar >= numChars) {
                        curChar = 0;
                        try {
                                numChars = stream.read(buf);
                        } catch (IOException e) {
                                throw new InputMismatchException();
                        }
                        if (numChars <= 0)
                                return -1;
                }
                return buf[curChar++];
        }

        public int peek() {
                if (numChars == -1)
                        return -1;
                if (curChar >= numChars) {
                        curChar = 0;
                        try {
                                numChars = stream.read(buf);
                        } catch (IOException e) {
                                return -1;
                        }
                        if (numChars <= 0)
                                return -1;
                }
                return buf[curChar];
        }

        public int ni() {
                int c = read();
                while (isSpaceChar(c))
                        c = read();
                int sgn = 1;
                if (c == '-') {
                        sgn = -1;
                        c = read();
                }
                int res = 0;
                do {
                        if (c < '0' || c > '9')
                                throw new InputMismatchException();
                        res *= 10;
                        res += c - '0';
                        c = read();
                } while (!isSpaceChar(c));
                return res * sgn;
        }

        public long nl() {
                int c = read();
                while (isSpaceChar(c))
                        c = read();
                int sgn = 1;
                if (c == '-') {
                        sgn = -1;
                        c = read();
                }
                long res = 0;
                do {
                        if (c < '0' || c > '9')
                                throw new InputMismatchException();
                        res *= 10;
                        res += c - '0';
                        c = read();
                } while (!isSpaceChar(c));
                return res * sgn;
        }

        public String ns() {
                int c = read();
                while (isSpaceChar(c))
                        c = read();
                StringBuilder res = new StringBuilder();
                do {
                        res.appendCodePoint(c);
                        c = read();
                } while (!isSpaceChar(c));
                return res.toString();
        }

        public boolean isSpaceChar(int c) {
                if (filter != null)
                        return filter.isSpaceChar(c);
                return isWhitespace(c);
        }

        public boolean isWhitespace(int c) {
                return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        private String readLine0() {
                StringBuilder buf = new StringBuilder();
                int c = read();
                while (c != '\n' && c != -1) {
                        if (c != '\r')
                                buf.appendCodePoint(c);
                        c = read();
                }
                return buf.toString();
        }

        public String readLine() {
                String s = readLine0();
                while (s.trim().length() == 0)
                        s = readLine0();
                return s;
        }

        public String readLine(boolean ignoreEmptyLines) {
                if (ignoreEmptyLines)
                        return readLine();
                else
                        return readLine0();
        }

        public BigInteger readBigInteger() {
                try {
                        return new BigInteger(ns());
                } catch (NumberFormatException e) {
                        throw new InputMismatchException();
                }
        }

        public char readCharacter() {
                int c = read();
                while (isSpaceChar(c))
                        c = read();
                return (char) c;
        }

        public double nd() {
                int c = read();
                while (isSpaceChar(c))
                        c = read();
                int sgn = 1;
                if (c == '-') {
                        sgn = -1;
                        c = read();
                }
                double res = 0;
                while (!isSpaceChar(c) && c != '.') {
                        if (c == 'e' || c == 'E')
                                return res * Math.pow(10, ni());
                        if (c < '0' || c > '9')
                                throw new InputMismatchException();
                        res *= 10;
                        res += c - '0';
                        c = read();
                }
                if (c == '.') {
                        c = read();
                        double m = 1;
                        while (!isSpaceChar(c)) {
                                if (c == 'e' || c == 'E')
                                        return res * Math.pow(10, ni());
                                if (c < '0' || c > '9')
                                        throw new InputMismatchException();
                                m /= 10;
                                res += (c - '0') * m;
                                c = read();
                        }
                }
                return res * sgn;
        }

        public boolean eof() {
                int value;
                while (isSpaceChar(value = peek()) && value != -1)
                        read();
                return value == -1;
        }

        public String next() {
                return ns();
        }

        public SpaceCharFilter getFilter() {
                return filter;
        }

        public void setFilter(SpaceCharFilter filter) {
                this.filter = filter;
        }

    }
    public interface SpaceCharFilter {
        public boolean isSpaceChar(int ch);
    }

}

import java.util.*;

public class D {

	private static long solve(long n, int m)
	{
		long mask = 0;
		long[] digMasks = new long[10];
		long[] digFullMasks = new long[10];

		for (long i = 0, t = 128; i < 10; ++i)
		{
			digMasks[(int)i] = t;
			digFullMasks[(int)i] = t*31;
			t <<= 5;
		}

		long t = n;
		int nd = 0;
		while (t > 0)
		{
			int d = (int)(t%10);
			mask += digMasks[d];
			t /= 10;
			++nd;
		}

		HashMap<Long, Long> h = new HashMap<Long, Long>(), e = new HashMap<Long, Long>(), f;
		h.put(mask, 1L);
		long l = 1;
		for (int i = 0; i < nd; ++i)
		{
			e.clear();
			for(Long key : h.keySet()) {
			    Long value = h.get(key);
			 //   System.out.println("" + i + " " + key + " " + value);
			    for (int d = 0; d < 10; ++d)
			    {
			    	if ( (key & digFullMasks[d]) == 0 )
			    		continue;
			    	long newkey = key - digMasks[d];
			    	long mod = newkey%128;
			    	mod = (mod + l*d)%m;
			    	newkey = newkey/128*128 + mod;
			    	if (newkey >= 128 && newkey < 128*32)
			    		continue;
			    	if (!e.containsKey(newkey))
			    		e.put(newkey, value);
			    	else
			    		e.put(newkey, value + e.get(newkey));
			    }
			}
			l = 10*l%m;
			f = e;
			e = h;
			h = f;
		}
		return h.containsKey(0L) ? h.get(0L) : 0L;
	}
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		long n = sc.nextLong();
		int m = sc.nextInt();
		System.out.println(solve(n, m));
	}

}

//package codeforces;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;

public class D implements Closeable {
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    PrintWriter writer = new PrintWriter(System.out);
    StringTokenizer stringTokenizer;

    String next() throws IOException {
        while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
            stringTokenizer = new StringTokenizer(reader.readLine());
        }
        return stringTokenizer.nextToken();
    }

    int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    long nextLong() throws IOException {
        return Long.parseLong(next());
    }

    private double nextDouble() throws IOException {
        return Double.parseDouble(next());
    }

    int MOD = 1000 * 1000 * 1000 + 7;

    int sum(int a, int b) {
        a += b;
        return a >= MOD ? a - MOD : a;
    }

    int product(int a, int b) {
        return (int) (1l * a * b % MOD);
    }

    @SuppressWarnings("unchecked")
    void solve() throws IOException {
        long n = nextLong();
        final int m = nextInt();
        List<Integer> digits = new ArrayList<>();
        for(long i = n; i > 0; i /= 10) {
            digits.add((int)(i % 10));
        }
        Collections.sort(digits);
        final int[] d = new int[digits.size()];
        for(int i = 0; i < digits.size(); i++) {
            d[i] = digits.get(i);
        }
        class Utils {
            final boolean bitIsSet(int mask, int bit) {
                return (mask & (1 << bit)) > 0;
            }

            long rec(int mask, int mod) {
                if(mask == (1 << d.length) - 1) {
                    return mod == 0 ? 1 : 0;
                }
                long result = 0;
                for(int i = 0; i < d.length; i++) {
                    if(mask == 0 && d[i] == 0) {
                        continue;
                    }
                    if(!bitIsSet(mask, i)) {
                        if(i > 0 && d[i] == d[i - 1] && !bitIsSet(mask, i - 1)) {
                            continue;
                        }
                        result += rec(mask | (1 << i), (mod * 10 + d[i]) % m);
                    }
                }
                return result;
            }
        }
        class CachedUtils extends Utils {
            boolean[][] hit = new boolean[1 << d.length][m];
            long[][] cache = new long[1 << d.length][m];

            @Override
            long rec(int mask, int mod) {
                if(!hit[mask][mod]) {
                    cache[mask][mod] = super.rec(mask, mod);
                    hit[mask][mod] = true;
                }
                return cache[mask][mod];
            }
        }
        writer.println(new CachedUtils().rec(0, 0));
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        try (D d = new D()) {
            d.solve();
        }
    }

    @Override
    public void close() throws IOException {
        reader.close();
        writer.close();
    }
}

import java.io.*;
import java.util.*;

import static java.lang.Math.*;
import static java.util.Arrays.*;

public class cf401d_2 {

    public static void main(String[] args) throws IOException {
        r();
        char[] nch = input.nextToken().toCharArray();
        int m = ni(), len = nch.length, n[] = new int[len];
        for(int i = 0; i < len; ++i) {
            n[i] = nch[i] - '0';
        }
        long fact[] = new long[len + 1], dp[][] = new long[1 << len][m];
        fact[0] = 1;
        for(int i = 1; i <= len; ++i) {
            fact[i] = fact[i - 1] * i;
        }
        dp[0][0] = 1;
        for(int i = 0; i < 1 << len; ++i) {
            for(int j = 0; j < len; ++j) {
                if((i & (1 << j)) == 0) {
                    for(int k = 0; k < m; ++k) {
                        if(i > 0 || n[j] > 0) {
                            dp[i | (1 << j)][(k * 10 + n[j]) % m] += dp[i][k];
                        }
                    }
                }
            }
        }
        long ans = dp[(1 << len) - 1][0];
        int[] cnt = new int[10];
        for(int i : n) {
            ++cnt[i];
        }
        for(int i = 0; i < 10; ++i) {
            ans /= fact[cnt[i]];
        }
        prln(ans);
        close();
    }

    static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in));
    static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));
    static StringTokenizer input;
    static Random rand = new Random();

    // references
    // IBIG = 1e9 + 7
    // IRAND ~= 3e8
    // IMAX ~= 2e10
    // LMAX ~= 9e18
    // constants
    static final int IBIG = 1000000007;
    static final int IRAND = 327859546;
    static final int IMAX = 2147483647;
    static final int IMIN = -2147483648;
    static final long LMAX = 9223372036854775807L;
    static final long LMIN = -9223372036854775808L;
    // util
    static int minof(int a, int b, int c) {return min(a, min(b, c));}
    static int minof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));}
    static int minstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));}
    static long minof(long a, long b, long c) {return min(a, min(b, c));}
    static long minof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));}
    static long minstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));}
    static int maxof(int a, int b, int c) {return max(a, max(b, c));}
    static int maxof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));}
    static int maxstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));}
    static long maxof(long a, long b, long c) {return max(a, max(b, c));}
    static long maxof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));}
    static long maxstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));}
    static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
    static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
    static int floori(double d) {return (int)d;}
    static int ceili(double d) {return (int)ceil(d);}
    static long floorl(double d) {return (long)d;}
    static long ceill(double d) {return (long)ceil(d);}
    static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
    static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
    static void shuffle(double[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
    static <T> void shuffle(T[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); T swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
    static void sort(int[] a) {shuffle(a); Arrays.sort(a);}
    static void sort(long[] a) {shuffle(a); Arrays.sort(a);}
    static void sort(double[] a) {shuffle(a); Arrays.sort(a);}
    static void qsort(int[] a) {Arrays.sort(a);}
    static void qsort(long[] a) {Arrays.sort(a);}
    static void qsort(double[] a) {Arrays.sort(a);}
    static int randInt(int min, int max) {return rand.nextInt(max - min + 1) + min;}
    // input
    static void r() throws IOException {input = new StringTokenizer(__in.readLine());}
    static int ri() throws IOException {return Integer.parseInt(__in.readLine());}
    static long rl() throws IOException {return Long.parseLong(__in.readLine());}
    static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;}
    static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;}
    static char[] rcha() throws IOException {return __in.readLine().toCharArray();}
    static String rline() throws IOException {return __in.readLine();}
    static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());}
    static int ni() {return Integer.parseInt(input.nextToken());}
    static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());}
    static long nl() {return Long.parseLong(input.nextToken());}
    // output
    static void pr(int i) {__out.print(i);}
    static void prln(int i) {__out.println(i);}
    static void pr(long l) {__out.print(l);}
    static void prln(long l) {__out.println(l);}
    static void pr(double d) {__out.print(d);}
    static void prln(double d) {__out.println(d);}
    static void pr(char c) {__out.print(c);}
    static void prln(char c) {__out.println(c);}
    static void pr(char[] s) {__out.print(new String(s));}
    static void prln(char[] s) {__out.println(new String(s));}
    static void pr(String s) {__out.print(s);}
    static void prln(String s) {__out.println(s);}
    static void pr(Object o) {__out.print(o);}
    static void prln(Object o) {__out.println(o);}
    static void prln() {__out.println();}
    static void pryes() {__out.println("yes");}
    static void pry() {__out.println("Yes");}
    static void prY() {__out.println("YES");}
    static void prno() {__out.println("no");}
    static void prn() {__out.println("No");}
    static void prN() {__out.println("NO");}
    static void pryesno(boolean b) {__out.println(b ? "yes" : "no");};
    static void pryn(boolean b) {__out.println(b ? "Yes" : "No");}
    static void prYN(boolean b) {__out.println(b ? "YES" : "NO");}
    static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
    static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
    static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); if(n >= 0) __out.println(iter.next());}
    static void h() {__out.println("hlfd");}
    static void flush() {__out.flush();}
    static void close() {__out.close();}
}

import java.io.*;
import java.util.*;

public class Main implements Runnable {
  final boolean isFileIO = false;
  BufferedReader in;
  PrintWriter out;
  StringTokenizer st = new StringTokenizer("");
  String delim = " ";

  public static void main(String[] args) {
    new Thread(null, new Main(), "", 268435456).start();
  }

  public void run() {
    try {
      initIO();
      solve();
      out.close();
    } catch(Exception e) {
      e.printStackTrace(System.err);
      System.exit(-1);
    }
  }

  public void initIO() throws IOException {
    if(!isFileIO) {
      in = new BufferedReader(new InputStreamReader(System.in));
      out = new PrintWriter(System.out);
    } else {
      in = new BufferedReader(new FileReader("input.txt"));
      out = new PrintWriter("output.txt");
    }
  }

  String nextToken() throws IOException {
    if(!st.hasMoreTokens()) {
      st = new StringTokenizer(in.readLine());
    }
    return st.nextToken(delim);
  }

  String readLine() throws IOException {
    return in.readLine();
  }

  int nextInt() throws IOException {
   return Integer.parseInt(nextToken());
  }

  long nextLong() throws IOException {
    return Long.parseLong(nextToken());
  }

  double nextDouble() throws IOException {
    return Double.parseDouble(nextToken());
  }

  void solve() throws IOException {
    long n; int m;
    n = nextLong(); m = nextInt();
    ArrayList<Integer> digits = new ArrayList<Integer>();
    long temp = n;
    while(temp != 0) {
      digits.add((int)(temp % 10));
      temp /= 10;
    }
    int cnt = digits.size();
    int max = 1 << cnt;
    long[][] dp = new long[max][m];
    long[] fact = new long[10];
    for(int i = 0; i < 10; i++) {
      int c = 0;
      for(int j = 0; j < cnt; j++)
        if(digits.get(j) == i) c++;
      fact[i] = 1;
      for(long j = 2; j <= c; j++)
        fact[i] = fact[i] * j;
    }
    for(int i = 0; i < cnt; i++) {
      int digit = digits.get(i);
      if(digit == 0) continue;
      dp[1 << i][digit % m] = 1;
    }
    for(int mask = 1; mask < max; mask++) {
      for(int j = 0; j < cnt; j++) {
        int cur = (1 << j);
        if((mask & cur) == cur) {
          for(int k = 0; k < m; k++) {
            dp[mask][(k * 10 + digits.get(j)) % m] += dp[mask ^ cur][k];
          }
        }
      }
    }
    long ans = 0;
    ans += dp[max - 1][0];
    for(int i = 0; i < 10; i++) {
      ans /= fact[i];
    }
    out.println(ans);
  }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.io.InputStream;

/**
 * @author khokharnikunj8
 */

public class Main {
    public static void main(String[] args) {
        new Thread(null, new Runnable() {
            public void run() {
                new Main().solve();
            }
        }, "1", 1 << 26).start();
    }

    void solve() {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        ScanReader in = new ScanReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        DRomanAndNumbers solver = new DRomanAndNumbers();
        solver.solve(1, in, out);
        out.close();
    }

    static class DRomanAndNumbers {
        public void solve(int testNumber, ScanReader in, PrintWriter out) {
            char[] s = in.scanString().toCharArray();
            int m = in.scanInt();
            long[][] dp = new long[1 << s.length][m];
            for (int i = 0; i < s.length; i++) {
                if (s[i] != '0') dp[1 << i][(s[i] - '0') % m] = 1;
            }
            long[] fact = new long[20];
            fact[0] = 1;
            for (int i = 1; i < 20; i++) fact[i] = fact[i - 1] * i;
            for (int i = 0; i < 1 << s.length; i++) {
                for (int j = 0; j < m; j++) {
                    if (dp[i][j] == 0) continue;
                    for (int k = 0; k < s.length; k++) {
                        if ((i & (1 << k)) == 0) {
                            dp[i ^ (1 << k)][(j * 10 + (s[k] - '0')) % m] += dp[i][j];
                        }
                    }
                }
            }
            long ans = dp[(1 << s.length) - 1][0];
            int[] count = new int[10];
            for (char c : s) count[c - '0']++;
            for (int i : count) ans /= fact[i];
            out.println(ans);

        }

    }

    static class ScanReader {
        private byte[] buf = new byte[4 * 1024];
        private int index;
        private BufferedInputStream in;
        private int total;

        public ScanReader(InputStream inputStream) {
            in = new BufferedInputStream(inputStream);
        }

        private int scan() {
            if (index >= total) {
                index = 0;
                try {
                    total = in.read(buf);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (total <= 0) return -1;
            }
            return buf[index++];
        }

        public int scanInt() {
            int integer = 0;
            int n = scan();
            while (isWhiteSpace(n)) n = scan();
            int neg = 1;
            if (n == '-') {
                neg = -1;
                n = scan();
            }
            while (!isWhiteSpace(n)) {
                if (n >= '0' && n <= '9') {
                    integer *= 10;
                    integer += n - '0';
                    n = scan();
                }
            }
            return neg * integer;
        }

        public String scanString() {
            int c = scan();
            if (c == -1) return null;
            while (isWhiteSpace(c)) c = scan();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = scan();
            } while (!isWhiteSpace(c));
            return res.toString();
        }

        private boolean isWhiteSpace(int n) {
            if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
            else return false;
        }

    }
}

//package round235;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;

public class D {
	InputStream is;
	PrintWriter out;
	String INPUT = "";

	void solve()
	{
		long n = nl();
		int m = ni();
		int[] ds = new int[Long.toString(n).length()];
		int p = 0;
		for(char c : Long.toString(n).toCharArray()){
			ds[p++] = c-'0';
		}
		Arrays.sort(ds);

		long[][] dp = new long[1<<p][m];
		dp[0][0] = 1;
		for(int i = 0;i < 1<<p;i++){
			for(int j = 0;j < m;j++){
				if(dp[i][j] == 0)continue;
				for(int k = 0;k < p;k++){
					if(i<<31-k>=0){
						if(i == 0 && ds[k] == 0)continue;
						if(k > 0 && ds[k] == ds[k-1] && i<<31-(k-1)>=0)continue;
						dp[i|1<<k][(j*10+ds[k])%m] += dp[i][j];
					}
				}
			}
		}
		out.println(dp[(1<<p)-1][0]);
	}

	void run() throws Exception
	{
		is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);

		long s = System.currentTimeMillis();
		solve();
		out.flush();
		tr(System.currentTimeMillis()-s+"ms");
	}

	public static void main(String[] args) throws Exception { new D().run(); }

	private byte[] inbuf = new byte[1024];
	private int lenbuf = 0, ptrbuf = 0;

	private int readByte()
	{
		if(lenbuf == -1)throw new InputMismatchException();
		if(ptrbuf >= lenbuf){
			ptrbuf = 0;
			try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
			if(lenbuf <= 0)return -1;
		}
		return inbuf[ptrbuf++];
	}

	private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
	private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }

	private double nd() { return Double.parseDouble(ns()); }
	private char nc() { return (char)skip(); }

	private String ns()
	{
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	private char[] ns(int n)
	{
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while(p < n && !(isSpaceChar(b))){
			buf[p++] = (char)b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}

	private char[][] nm(int n, int m)
	{
		char[][] map = new char[n][];
		for(int i = 0;i < n;i++)map[i] = ns(m);
		return map;
	}

	private int[] na(int n)
	{
		int[] a = new int[n];
		for(int i = 0;i < n;i++)a[i] = ni();
		return a;
	}

	private int ni()
	{
		int num = 0, b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}

		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private long nl()
	{
		long num = 0;
		int b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}

		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
	private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}

import java.io.IOException;
import java.util.Arrays;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Mahmoud Aladdin <aladdin3>
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		PrintWriter out = new PrintWriter(outputStream);
		TaskD solver = new TaskD();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskD {
    int[] input;
    int m;

    long[][] memory = new long[(1 << 18)][101];

    public void solve(int testNumber, InputReader jin, PrintWriter jout) {
        String token = jin.token();
        m = jin.int32();

        input = new int[token.length()];
        for(int i = 0; i < token.length(); i++) {
            input[i] = token.charAt(i) - '0';
        }

        for(long[] r: memory) Arrays.fill(r, -1);

        BigInteger mask = BigInteger.ZERO;
        BigInteger curr = BigInteger.ZERO;
        long res = 0;
        for(int i = 0; i < input.length; i++) {
            if(input[i] != 0) {
                if(curr.testBit(input[i])) continue;
                curr = curr.setBit(input[i]);
                res += bt(mask.setBit(i), input[i] % m, input[i]);
            }
        }
        jout.println(res);
    }

    private long bt(BigInteger mask, int rem, long val) {
        if(mask.intValue() == (1 << input.length) - 1) {
            return rem == 0? 1: 0;
        } else {
            if(memory[mask.intValue()][rem] != -1)
                return memory[mask.intValue()][rem];
            long res = 0;
            BigInteger currMask = BigInteger.ZERO;
            for(int i = 0; i < input.length; i++) {
                if(mask.testBit(i)) continue;
                if(currMask.testBit(input[i])) continue;
                currMask = currMask.setBit(input[i]);
                res += bt(mask.setBit(i), ((rem * 10) + input[i]) % m, val * 10 + input[i]);
            }
            return memory[mask.intValue()][rem] = res;
        }
    }
}

class InputReader {
    private static final int bufferMaxLength = 1024;
    private InputStream in;
    private byte[] buffer;
    private int currentBufferSize;
    private int currentBufferTop;
    private static final String tokenizers = " \t\r\f\n";

    public InputReader(InputStream stream) {
        this.in = stream;
        buffer = new byte[bufferMaxLength];
        currentBufferSize = 0;
        currentBufferTop = 0;
    }

    private boolean refill() {
        try {
            this.currentBufferSize = this.in.read(this.buffer);
            this.currentBufferTop = 0;
        } catch(Exception e) {}
        return this.currentBufferSize > 0;
    }

    private Byte readChar() {
        if(currentBufferTop < currentBufferSize) {
            return this.buffer[this.currentBufferTop++];
        } else {
            if(!this.refill()) {
                return null;
            } else {
                return readChar();
            }
        }
    }

    public String token()  {
        StringBuffer tok = new StringBuffer();
        Byte first;
        while((first = readChar()) != null && (tokenizers.indexOf((char) first.byteValue()) != -1));
        if(first == null) return null;
        tok.append((char)first.byteValue());
        while((first = readChar()) != null && (tokenizers.indexOf((char) first.byteValue()) == -1)) {
            tok.append((char)first.byteValue());
        }
        return tok.toString();
    }

    public Integer int32() throws NumberFormatException {
        String tok = token();
        return tok == null? null : Integer.parseInt(tok);
    }

    }

import java.io.*;
import java.util.*;

public class C235D
{
    public static StringTokenizer st;
    public static void nextLine(BufferedReader br) throws IOException
    {
        st = new StringTokenizer(br.readLine());
    }

    public static String next()
    {
        return st.nextToken();
    }

    public static int nextInt()
    {
        return Integer.parseInt(st.nextToken());
    }

    public static long nextLong()
    {
        return Long.parseLong(st.nextToken());
    }

    public static double nextDouble()
    {
        return Double.parseDouble(st.nextToken());
    }

    static long[][] dp;
    static long[] md;
    static int[] d, cd;
    static long[][] modx;
    static long m;

    public static void main(String[] args) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        nextLine(br);
        long n = nextLong();
        m = nextLong();
        d = new int[10];
        long copy = n;
        int nd = 0;
        while (copy > 0)
        {
            d[(int)(copy % 10)]++;
            copy /= 10;
            nd++;
        }
        cd = new int[10];
        cd[0] = d[0];
        for (int i = 1; i < 10; i++)
        {
            cd[i] = cd[i-1] + d[i];
        }
        md = new long[10];
        md[0] = d[0] + 1;
        for (int i = 1; i < 10; i++)
        {
            md[i] = md[i-1] * (d[i] + 1);
        }
        long total = 0;
        modx = new long[10][18];
        for (int i = 0; i < 10; i++)
        {
            long val = i;
            for (int j = 0; j < 18; j++)
            {
                modx[i][j] = val % m;
                val *= 10;
            }
        }
        dp = new long[(int)md[9]][(int)m];
        for (int i = 0; i < dp.length; i++)
        {
            Arrays.fill(dp[i], -1);
        }
        for (int i = 1; i <= 9; i++)
        {
            if (d[i] == 0) continue;
            long val = md[9] - (i == 0 ? 1 : md[i-1]) - 1;
            total += solve(val, (int)((m - modx[i][nd-1]) % m), nd - 1);
        }
        System.out.println(total);
    }

    private static long solve(long val, int rem, int digits)
    {
        //System.out.println("calling " + val + " " + rem + " " + digits);
        if (dp[(int)val][rem] != -1)
        {
            return dp[(int)val][rem];
        }
        if (digits == 0)
        {
            return rem == 0 ? 1 : 0;
        }
        long total = 0;
        for (int i = 0; i < 10; i++)
        {
            long num = (val % md[i]) / (i == 0 ? 1 : md[i-1]);
            if (num == 0) continue;
            total += solve(val - (i == 0 ? 1 : md[i-1]),
                    (int)(m + rem - modx[i][digits - 1]) % (int)m, digits - 1);
        }
        dp[(int)val][rem] = total;
        return total;
    }
}

import java.util.*;
import java.io.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
import static java.lang.Math.*;

public class D {

	int INF = 1 << 28;
	//long INF = 1L << 62;
	double EPS = 1e-10;
	ExMap[] maps;

	void run() {
		maps = new ExMap[2];
		maps[0] = new ExMap(); maps[1] = new ExMap();
		Scanner sc = new Scanner(System.in);
		String n = sc.next();int m = sc.nextInt();
		int[] ns = new int[10]; int l = n.length();
		for(int i=0;i<l;i++) ns[n.charAt(i) - '0']++;

		long[] pow = new long[10]; pow[0] = 1;
		for(int i=1;i<10;i++) pow[i] = pow[i-1] * 20;

		long ndig = 0;
		for(int i=0;i<10;i++) ndig += pow[i] * ns[i];

		long[] dp = new long[m]; dp[0] = 1;
		maps[0].put(ndig, dp);
		int x = 1;
		long[] val, tar; long key;
		for(int i=0;i<l;i++) {
			maps[x].clear();
			for(Map.Entry<Long, long[]> entry: maps[1-x].entrySet()) {
				key = entry.getKey();
				tar = entry.getValue();
				for(int j=(i==0? 1: 0);j<10;j++) if((key / pow[j]) % 20 > 0) {

					if(maps[x].containsKey(key - pow[j])) val = maps[x].get(key - pow[j]);
					else val = new long[m];
					for(int k=0;k<m;k++) val[(k*10 + j) % m] += tar[k];

					maps[x].put(key - pow[j], val);
				}
			}
			x = 1-x;
		}
		for(Map.Entry<Long, long[]> entry: maps[1-x].entrySet()) {
			tar = entry.getValue();
			long ans = tar[0];
			System.out.println(ans);
		}
	}

	class ExMap extends HashMap<Long, long[]>{}

	void debug(Object... os) {
		System.err.println(Arrays.deepToString(os));
	}

	public static void main(String[] args) {
		new D().run();
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;

	public class Abood2C {
		static int N;
		static long memo[][][][][][][][][][][][];
		static int MOD;
		static long solve(int i, int[] r, int m) {
			if(i == N && m == 0)
				return 1;
			if(i == N)
				return 0;
			if(memo[i][r[0]][r[1]][r[2]][r[3]][r[4]][r[5]][r[6]][r[7]][r[8]][r[9]][m] != -1)
				return memo[i][r[0]][r[1]][r[2]][r[3]][r[4]][r[5]][r[6]][r[7]][r[8]][r[9]][m];

			long ans = 0;
			int[] v = r.clone();
			int p = 1;
			for (int j = 0; j < i; j++) {
				p *= 10;
				p %= MOD;
			}
			for (int j = 0; j < r.length; j++) {
				if(r[j] == 0 || j == 0 && i == N - 1)
					continue;
				v[j]--;
				ans += solve(i + 1, v, (m + p * j) % MOD);
				v[j]++;
			}
			return memo[i][r[0]][r[1]][r[2]][r[3]][r[4]][r[5]][r[6]][r[7]][r[8]][r[9]][m] = ans;
		}

		public static void main(String[] args) throws Exception{
			Scanner sc = new Scanner(System.in);
			PrintWriter out = new PrintWriter(System.out);

			String s = sc.next();
			N = s.length();
			MOD = sc.nextInt();

			int[] r = new int[10];
			for (int i = 0; i < s.length(); i++)
				r[s.charAt(i) - '0']++;
			memo = new long [N][r[0] + 1][r[1] + 1][r[2] + 1][r[3] + 1][r[4] + 1][r[5] + 1][r[6] + 1][r[7] + 1][r[8] + 1][r[9] + 1][MOD];
			for (int i = 0; i < N; i++)
				for (int j = 0; j <= r[0]; j++)
					for (int j2 = 0; j2 <= r[1]; j2++)
						for (int k = 0; k <= r[2]; k++)
							for (int k2 = 0; k2 <= r[3]; k2++)
								for (int l = 0; l <= r[4]; l++)
									for (int l2 = 0; l2 <= r[5]; l2++)
										for (int m = 0; m <= r[6]; m++)
											for (int m2 = 0; m2 <= r[7]; m2++)
												for (int o = 0; o <= r[8]; o++)
													for (int o2 = 0; o2 <= r[9]; o2++)
															Arrays.fill(memo[i][j][j2][k][k2][l][l2][m][m2][o][o2], -1);

			out.println(solve(0, r, 0));

			out.flush();
			out.close();
		}

		static class Scanner
		{
			StringTokenizer st;
			BufferedReader br;

			public Scanner(InputStream System){	br = new BufferedReader(new InputStreamReader(System));}
			public String next() throws IOException
			{
				while (st == null || !st.hasMoreTokens())
					st = new StringTokenizer(br.readLine());
				return st.nextToken();
			}
			public String nextLine()throws IOException{return br.readLine();}
			public int nextInt() throws IOException {return Integer.parseInt(next());}
			public double nextDouble() throws IOException {return Double.parseDouble(next());}
			public char nextChar()throws IOException{return next().charAt(0);}
			public Long nextLong()throws IOException{return Long.parseLong(next());}
			public boolean ready() throws IOException{return br.ready();}
			public void waitForInput(){for(long i = 0; i < 3e9; i++);}
		}
	}

import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Scanner;

/**
 * Built using CHelper plug-in Actual solution is at the top
 */
public class Main {
	public static void main(String[] args) {
		TaskD t = new TaskD();
		t.solve();
	}
}

class TaskD {
	long ways[][];
	char no[];
	int m;
	int len;
	LinkedList<Integer>[][] asdf;

	public void solve() {
		Scanner scan = new Scanner(System.in);
		no = (scan.nextLong() + "").toCharArray();
		len = no.length;
		m = scan.nextInt();
		ways = new long[1 << len][m];
		for (long[] a : ways)
			Arrays.fill(a, -1);

		// this code is so ugly, but i'm so sleep deprived
		asdf = new LinkedList[10][m];
		for(int k=0; k < asdf.length; k++){
			for(int rem=0; rem < asdf[k].length; rem++){
				asdf[k][rem] = new LinkedList<Integer>();
				for(int j=0; j < m; j++){
					if((j * 10 + k) % m == rem){
						asdf[k][rem].add(j);
					}

				}
			}
		}

		System.out.println(waysToGetRemWithNums((1 << len) - 1, 0, 0));
//		for (int i = ways.length - 1; i >= 0; i--) {
//			System.out.println(Integer.toBinaryString(i) + ": " + Arrays.toString(ways[i]));
//		}
	}

	long waysToGetRemWithNums(int mask, int rem, int depth) {
		depth++;
		String tabs = "";
//		for (int i = 0; i < depth; i++, tabs = tabs + "\t")	;
		// rem = rem*10%m;
		if (mask == 0) {
			if (rem == 0) {
				ways[mask][rem] = 1;
				return 1;
			}
			ways[mask][rem] = 0;
			return 0;
		}
		if (ways[mask][rem] != -1)
			return ways[mask][rem];
		long ans = 0;
		HashSet<Character> charsUsed = new HashSet<Character>();
		// System.out.println(tabs + "how many ways with mask " + Integer.toBinaryString(mask) + " to make remainder " + rem +"?");
		for (int i = 0; i < len; i++) {
			if (((mask >> i) & 1) == 0)
				continue;
			if (depth == len && no[i] == '0')
				continue;
			if (charsUsed.contains(no[i]))
				continue;
			charsUsed.add(no[i]);
			// find the remainder that solves (r1*10 + k) %M == r0
			int k = no[i] - '0';
			for (Integer j : asdf[k][rem]) {
				int remainderNeeded = j;
				// System.out.println(tabs + "need to make mask " + Integer.toBinaryString((mask & ~(1<<i))));
				// System.out.println(tabs + " with remainder " + remainderNeeded);

				ans += waysToGetRemWithNums(mask & ~(1 << i), remainderNeeded, depth);
				// ans += go(mask | (1 << i), ((rem * 10) + no[i] - '0') % m);
			}
		}
		// System.out.println(tabs + "ans: " + ans);
		return ways[mask][rem] = ans;
	}

}

import java.util.*;
import java.io.*;

public class TaskD {
    private FastScanner in;
    private PrintWriter out;
    private int MAX_SIZE;

    public void solve() throws IOException {
        long n = in.nextLong(), m = in.nextLong();
        char[] data = Long.toString(n).toCharArray();
        int[] digits = new int[data.length];
        int[] count = new int[10];
        for (int i = 0; i < data.length; i++) {
            digits[i] = data[i] - '0';
            count[digits[i]]++;
        }
        MAX_SIZE = digits.length;
        long[][] dp = new long[1 << MAX_SIZE][(int) m];
        dp[0][0] = 1;

        for (int i = 0; i < 1 << MAX_SIZE; i++) {
            for (int j = 0; j < MAX_SIZE; j++) {
                if ((i & (1 << j)) == 0 && !(i == 0 && digits[j] == 0)) {
                    int to = (i | (1 << j));
                    for (int k = 0; k < m; k++) {
                        dp[to][(int) (((k * 10) + digits[j]) % m)] += dp[i][k];
                    }
                }
            }
        }
        long ans = dp[(1 << MAX_SIZE) - 1][0];
        for (int i = 0; i < 10; i++) {
            ans /= fact(count[i]);
        }
        out.print(ans);
    }

    long fact(int value) {
        long res = 1;
        for (int i = 1; i <= value; i++) {
            res *= i;
        }
        return res;
    }

    public void run() {
        try {
            in = new FastScanner();
            out = new PrintWriter(System.out);
            solve();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private class FastScanner {
        private BufferedReader br;
        private StringTokenizer st;

        public FastScanner() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        public String next() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

        public long nextLong() {
            return Long.parseLong(next());
        }

        public double nextDouble() {
            return Double.parseDouble(next());
        }

    }

    public static void main(String[] arg) {
        new TaskD().run();
    }
}

import java.util.Arrays; import java.util.Scanner; public class cf401d_10DIMENSIONSBABY { static int[] digitcounts = new int[10]; static int len, mod; static long[][][][][][][][][][][] memo; public static long dp(int[] counts, int cmod) { if (memo[counts[0]][counts[1]][counts[2]][counts[3]][counts[4]][counts[5]][counts[6]][counts[7]][counts[8]][counts[9]][cmod] != -1) { return memo[counts[0]][counts[1]][counts[2]][counts[3]][counts[4]][counts[5]][counts[6]][counts[7]][counts[8]][counts[9]][cmod]; } long tot = 0; for (int i = 0; i < 10; i++) { if (counts[i] < digitcounts[i]) { counts[i]++; tot += dp(counts, ((10 * cmod) + i) % mod); counts[i]--; } } memo[counts[0]][counts[1]][counts[2]][counts[3]][counts[4]][counts[5]][counts[6]][counts[7]][counts[8]][counts[9]][cmod] = tot; return tot; } public static long fact(int i) { long res = 1; for (int j = 2; j <= i; j++) res *= j; return res; } public static void main(String[] args) { Scanner s = new Scanner(System.in); long N = s.nextLong(); mod = s.nextInt(); String Nrep = "" + N; len = Nrep.length(); for (char i : Nrep.toCharArray()) digitcounts[i - '0']++; memo = new long[digitcounts[0] + 1][digitcounts[1] + 1][digitcounts[2] + 1][digitcounts[3] + 1][digitcounts[4] + 1][digitcounts[5] + 1][digitcounts[6] + 1][digitcounts[7] + 1][digitcounts[8] + 1][digitcounts[9] + 1][mod]; for (long[][][][][][][][][][] a : memo) for (long[][][][][][][][][] b : a) for (long[][][][][][][][] c : b) for (long[][][][][][][] d : c) for (long[][][][][][] e : d) for (long[][][][][] f : e) for (long[][][][] g : f) for (long[][][] h : g) for (long[][] i : h) for (long[] j : i) Arrays.fill(j, -1); Arrays.fill( memo[digitcounts[0]][digitcounts[1]][digitcounts[2]][digitcounts[3]][digitcounts[4]][digitcounts[5]][digitcounts[6]][digitcounts[7]][digitcounts[8]][digitcounts[9]], 0); memo[digitcounts[0]][digitcounts[1]][digitcounts[2]][digitcounts[3]][digitcounts[4]][digitcounts[5]][digitcounts[6]][digitcounts[7]][digitcounts[8]][digitcounts[9]][0] = 1; long res = 0; for (int i = 1; i < 10; i++) { if (digitcounts[i] != 0) { int[] count = new int[10]; count[i]++; res += dp(count, i % mod); } } System.out.println(res); s.close(); } }

import java.util.Arrays;
import java.util.Scanner;

public class cf401d_10DIMENSIONSBABY {

	static int[] digitcounts = new int[10];
	static int len, mod;
	static long[][][][][][][][][][][] memo;

	public static long dp(int[] counts, int cmod) {
		if (memo[counts[0]][counts[1]][counts[2]][counts[3]][counts[4]][counts[5]][counts[6]][counts[7]][counts[8]][counts[9]][cmod] != -1) {
			// System.out.println(Arrays.toString(counts) + " (" + cmod + ") -->
			// "
			// +
			// memo[counts[0]][counts[1]][counts[2]][counts[3]][counts[4]][counts[5]][counts[6]][counts[7]][counts[8]][counts[9]][cmod]);
			return memo[counts[0]][counts[1]][counts[2]][counts[3]][counts[4]][counts[5]][counts[6]][counts[7]][counts[8]][counts[9]][cmod];
		}
		long tot = 0;
		// try adding each digit
		for (int i = 0; i < 10; i++) {
			if (counts[i] < digitcounts[i]) {
				counts[i]++;
				// System.out.println(cmod + " --(" + i + ")--> " + (((10 *
				// cmod) + i) % mod));
				tot += dp(counts, ((10 * cmod) + i) % mod);
				counts[i]--;
			}
		}
		memo[counts[0]][counts[1]][counts[2]][counts[3]][counts[4]][counts[5]][counts[6]][counts[7]][counts[8]][counts[9]][cmod] = tot;
		return tot;
	}

	public static long fact(int i) {
		long res = 1;
		for (int j = 2; j <= i; j++)
			res *= j;
		return res;
	}

	public static void main(String[] args) {

		Scanner s = new Scanner(System.in);

		long N = s.nextLong();
		mod = s.nextInt();
		String Nrep = "" + N;
		len = Nrep.length();
		for (char i : Nrep.toCharArray())
			digitcounts[i - '0']++;

		memo = new long[digitcounts[0] + 1][digitcounts[1] + 1][digitcounts[2] + 1][digitcounts[3] + 1][digitcounts[4]
				+ 1][digitcounts[5] + 1][digitcounts[6] + 1][digitcounts[7] + 1][digitcounts[8] + 1][digitcounts[9]
						+ 1][mod];
		for (long[][][][][][][][][][] a : memo)
			for (long[][][][][][][][][] b : a)
				for (long[][][][][][][][] c : b)
					for (long[][][][][][][] d : c)
						for (long[][][][][][] e : d)
							for (long[][][][][] f : e)
								for (long[][][][] g : f)
									for (long[][][] h : g)
										for (long[][] i : h)
											for (long[] j : i)
												Arrays.fill(j, -1);
		Arrays.fill(
				memo[digitcounts[0]][digitcounts[1]][digitcounts[2]][digitcounts[3]][digitcounts[4]][digitcounts[5]][digitcounts[6]][digitcounts[7]][digitcounts[8]][digitcounts[9]],
				0);
		memo[digitcounts[0]][digitcounts[1]][digitcounts[2]][digitcounts[3]][digitcounts[4]][digitcounts[5]][digitcounts[6]][digitcounts[7]][digitcounts[8]][digitcounts[9]][0] = 1;
		long res = 0;
		for (int i = 1; i < 10; i++) {
			if (digitcounts[i] != 0) {
				int[] count = new int[10];
				count[i]++;
				res += dp(count, i % mod);
			}
		}
		// for (int g : digitcounts) {
		// res /= fact(g);
		// }
		System.out.println(res);

		// for (long[][][][][][][][][][] a : memo)
		// for (long[][][][][][][][][] b : a)
		// for (long[][][][][][][][] c : b)
		// for (long[][][][][][][] d : c)
		// for (long[][][][][][] e : d)
		// for (long[][][][][] f : e)
		// for (long[][][][] g : f)
		// for (long[][][] h : g)
		// for (long[][] i : h)
		// for (long[] j : i)
		// System.out.println(Arrays.toString(j));

		s.close();

	}

}

/**
 * DA-IICT
 * Author : PARTH PATEL
 */
import java.io.*;
import java.math.*;
import java.util.*;

import static java.util.Arrays.fill;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;

public class D401 {

	public static int mod = 1000000007;
	static FasterScanner in = new FasterScanner();
	static PrintWriter out = new PrintWriter(System.out);
	public static long factorial(long n)
	{
		if(n==0)
			return 1;
		else
			return n*factorial(n-1);
	}
	public static void main(String[] args) {

		String s=in.nextString();
		int m=in.nextInt();
		char[] arr=s.toCharArray();
		int n=arr.length;
		long[][] dp=new long[1<<n][m];
		dp[0][0]=1;
		for(int i=0;i<(1<<n);i++)
		{
			for(int j=0;j<m;j++)
			{
				if(dp[i][j]==0)
				{
					//in mask i there is no element with mod value j=(i%m)
					continue;
				}
				for(int k=0;k<n;k++)
				{
					if((i & (1<<k))==0)
					{
						//there should not be zero initially
						if(i==0 && arr[k]=='0')
							continue;
						//kth bit is not there in mask i. So we can include it
						dp[i|(1<<k)][(j*10+arr[k]-'0')%m]+=dp[i][j];
					}
				}
			}
		}
		long answer=dp[(1<<n)-1][0];
		int[] frequency=new int[10];
		for(int i=0;i<n;i++)
		{
			frequency[arr[i]-'0']++;
		}
		for(int i=0;i<10;i++)
		{
			answer/=(factorial(frequency[i]));
		}
		out.println(answer);
		out.close();

	}

	public static long pow(long x, long n, long mod) {
		long res = 1;
		for (long p = x; n > 0; n >>= 1, p = (p * p) % mod) {
			if ((n & 1) != 0) {
				res = (res * p % mod);
			}
		}
		return res;
	}

	public static long gcd(long n1, long n2) {
		long r;
		while (n2 != 0) {
			r = n1 % n2;
			n1 = n2;
			n2 = r;
		}
		return n1;
	}

	public static long lcm(long n1, long n2) {
		long answer = (n1 * n2) / (gcd(n1, n2));
		return answer;
	}

	static class FasterScanner {
		private byte[] buf = new byte[1024];
		private int curChar;
		private int snumChars;

		public int read() {
			if (snumChars == -1)
				throw new InputMismatchException();
			if (curChar >= snumChars) {
				curChar = 0;
				try {
					snumChars = System.in.read(buf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (snumChars <= 0)
					return -1;
			}
			return buf[curChar++];
		}

		public String nextLine() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isEndOfLine(c));
			return res.toString();
		}

		public String nextString() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		public long nextLong() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = read();
			}
			long res = 0;
			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public int nextInt() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = read();
			}
			int res = 0;
			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public int[] nextIntArray(int n) {
			int[] arr = new int[n];
			for (int i = 0; i < n; i++) {
				arr[i] = nextInt();
			}
			return arr;
		}

		public long[] nextLongArray(int n) {
			long[] arr = new long[n];
			for (int i = 0; i < n; i++) {
				arr[i] = nextLong();
			}
			return arr;
		}

		private boolean isSpaceChar(int c) {
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		private boolean isEndOfLine(int c) {
			return c == '\n' || c == '\r' || c == -1;
		}
	}

}

import java.util.*;
import java.io.*;
import java.awt.Point;
import java.math.BigDecimal;
import java.math.BigInteger;

import static java.lang.Math.*;

// Solution is at the bottom of code

public class D implements Runnable{

	final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

	BufferedReader in;
	OutputWriter out;
	StringTokenizer tok = new StringTokenizer("");

	public static void main(String[] args){
		new Thread(null, new D(), "", 128 * (1L << 20)).start();
	}

	/////////////////////////////////////////////////////////////////////

	void init() throws FileNotFoundException{
		Locale.setDefault(Locale.US);

		if (ONLINE_JUDGE){
			in = new BufferedReader(new InputStreamReader(System.in));
			out = new OutputWriter(System.out);
		}else{
			in = new BufferedReader(new FileReader("input.txt"));
			out = new OutputWriter("output.txt");
		}
	}

	////////////////////////////////////////////////////////////////

	long timeBegin, timeEnd;

	void time(){
		timeEnd = System.currentTimeMillis();
		System.err.println("Time = " + (timeEnd - timeBegin));
	}

	void debug(Object... objects){
		if (ONLINE_JUDGE){
			for (Object o: objects){
				System.err.println(o.toString());
			}
		}
	}

	/////////////////////////////////////////////////////////////////////

	public void run(){
		try{
			timeBegin = System.currentTimeMillis();
			Locale.setDefault(Locale.US);

			init();
			solve();

			out.close();
			time();
		}catch (Exception e){
			e.printStackTrace(System.err);
			System.exit(-1);
		}
	}

	/////////////////////////////////////////////////////////////////////

	String delim = " ";

	String readString() throws IOException{
		while(!tok.hasMoreTokens()){
			try{
				tok = new StringTokenizer(in.readLine());
			}catch (Exception e){
				return null;
			}
		}

		return tok.nextToken(delim);
	}

	String readLine() throws IOException{
		return in.readLine();
	}

	/////////////////////////////////////////////////////////////////

	final char NOT_A_SYMBOL = '\0';

	char readChar() throws IOException{
		int intValue = in.read();

		if (intValue == -1){
			return NOT_A_SYMBOL;
		}

		return (char) intValue;
	}

	char[] readCharArray() throws IOException{
		return readLine().toCharArray();
	}

	/////////////////////////////////////////////////////////////////

	int readInt() throws IOException {
		return Integer.parseInt(readString());
	}

	int[] readIntArray(int size) throws IOException {
		int[] array = new int[size];

		for (int index = 0; index < size; ++index){
			array[index] = readInt();
		}

		return array;
	}

	int[] readIntArrayWithDecrease(int size) throws IOException {
		int[] array = readIntArray(size);

		for (int i = 0; i < size; ++i) {
			array[i]--;
		}

		return array;
	}

	///////////////////////////////////////////////////////////////////

	long readLong() throws IOException{
		return Long.parseLong(readString());
	}

	long[] readLongArray(int size) throws IOException{
		long[] array = new long[size];

		for (int index = 0; index < size; ++index){
			array[index] = readLong();
		}

		return array;
	}

	////////////////////////////////////////////////////////////////////

	double readDouble() throws IOException{
		return Double.parseDouble(readString());
	}

	double[] readDoubleArray(int size) throws IOException{
		double[] array = new double[size];

		for (int index = 0; index < size; ++index){
			array[index] = readDouble();
		}

		return array;
	}

	////////////////////////////////////////////////////////////////////

	BigInteger readBigInteger() throws IOException {
		return new BigInteger(readString());
	}

	BigDecimal readBigDecimal() throws IOException {
		return new BigDecimal(readString());
	}

	/////////////////////////////////////////////////////////////////////

	Point readPoint() throws IOException{
		int x = readInt();
		int y = readInt();
		return new Point(x, y);
	}

	Point[] readPointArray(int size) throws IOException{
		Point[] array = new Point[size];

		for (int index = 0; index < size; ++index){
			array[index] = readPoint();
		}

		return array;
	}

	/////////////////////////////////////////////////////////////////////

	List<Integer>[] readGraph(int vertexNumber, int edgeNumber)
	throws IOException{
		@SuppressWarnings("unchecked")
		List<Integer>[] graph = new List[vertexNumber];

		for (int index = 0; index < vertexNumber; ++index){
			graph[index] = new ArrayList<Integer>();
		}

		while (edgeNumber-- > 0){
			int from = readInt() - 1;
			int to = readInt() - 1;

			graph[from].add(to);
			graph[to].add(from);
		}

		return graph;
	}

	/////////////////////////////////////////////////////////////////////

	static class IntIndexPair {

		static Comparator<IntIndexPair> increaseComparator = new Comparator<D.IntIndexPair>() {

			@Override
			public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) {
				int value1 = indexPair1.value;
				int value2 = indexPair2.value;

				if (value1 != value2) return value1 - value2;

				int index1 = indexPair1.index;
				int index2 = indexPair2.index;

				return index1 - index2;
			}
		};

		static Comparator<IntIndexPair> decreaseComparator = new Comparator<D.IntIndexPair>() {

			@Override
			public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) {
				int value1 = indexPair1.value;
				int value2 = indexPair2.value;

				if (value1 != value2) return -(value1 - value2);

				int index1 = indexPair1.index;
				int index2 = indexPair2.index;

				return index1 - index2;
			}
		};

		int value, index;

		public IntIndexPair(int value, int index) {
			super();
			this.value = value;
			this.index = index;
		}

		public int getRealIndex() {
			return index + 1;
		}
	}

	IntIndexPair[] readIntIndexArray(int size) throws IOException {
		IntIndexPair[] array = new IntIndexPair[size];

		for (int index = 0; index < size; ++index) {
			array[index] = new IntIndexPair(readInt(), index);
		}

		return array;
	}

	/////////////////////////////////////////////////////////////////////

	static class OutputWriter extends PrintWriter{

		final int DEFAULT_PRECISION = 12;

		int precision;
		String format, formatWithSpace;

		{
			precision = DEFAULT_PRECISION;

			format = createFormat(precision);
			formatWithSpace = format + " ";
		}

		public OutputWriter(OutputStream out) {
			super(out);
		}

		public OutputWriter(String fileName) throws FileNotFoundException {
			super(fileName);
		}

		public int getPrecision() {
			return precision;
		}

		public void setPrecision(int precision) {
			precision = max(0, precision);
			this.precision = precision;

			format = createFormat(precision);
			formatWithSpace = format + " ";
		}

		private String createFormat(int precision){
			return "%." + precision + "f";
		}

		@Override
		public void print(double d){
			printf(format, d);
		}

		public void printWithSpace(double d){
			printf(formatWithSpace, d);
		}

		public void printAll(double...d){
			for (int i = 0; i < d.length - 1; ++i){
				printWithSpace(d[i]);
			}

			print(d[d.length - 1]);
		}

		@Override
		public void println(double d){
			printlnAll(d);
		}

		public void printlnAll(double... d){
			printAll(d);
			println();
		}
	}

	/////////////////////////////////////////////////////////////////////

	int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
	int[][] steps8 = {
			{-1, 0}, {1, 0}, {0, -1}, {0, 1},
			{-1, -1}, {1, 1}, {1, -1}, {-1, 1}
	};

	boolean check(int index, int lim){
		return (0 <= index && index < lim);
	}

	/////////////////////////////////////////////////////////////////////

	boolean checkBit(int mask, int bit){
		return (mask & (1 << bit)) != 0;
	}

	/////////////////////////////////////////////////////////////////////

	void solve() throws IOException {
		char[] number = readString().toCharArray();
		int n = number.length;

		int md = readInt();

		int lim = (1 << n);
		long[][] dp = new long[lim][md];
		dp[0][0] = 1;

		int[] pows = new int[n];
		pows[0] = 1;
		for (int i = 1; i < n; ++i) {
			pows[i] = pows[i-1] * 10 % md;
		}

		int[] used = new int[10];

		for (int mask = 1; mask < lim; ++mask) {
			int pow = pows[n - Integer.bitCount(mask)];

			for (int bit = 0; bit < n; ++bit) {
				int digit = number[bit] - '0';

				if (checkBit(mask, bit) && used[digit] != mask) {
					int fromMask = (mask ^ (1 << bit));

					if (digit == 0 && fromMask == 0) {
						// bad idea
					} else {
						used[digit] = mask;

						for (int fromRem = 0; fromRem < md; ++fromRem) {
							int curRem = (fromRem + digit * pow) % md;
							dp[mask][curRem] = (dp[mask][curRem] + dp[fromMask][fromRem]);
						}
					}
				}
			}
		}

		long ans = dp[lim-1][0];
		out.println(ans);
	}
}

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;

public class l083 {

	private static long[] pow10 = new long[19];

	public static void main(String[] args) throws Exception {
//		StringTokenizer stok = new StringTokenizer(new Scanner(new File("F:/books/input.txt")).useDelimiter("\\A").next());
		StringTokenizer stok = new StringTokenizer(new Scanner(System.in).useDelimiter("\\A").next());
		StringBuilder sb = new StringBuilder();
		Long n = Long.parseLong(stok.nextToken());
		int m = Integer.parseInt(stok.nextToken());
		pow10[0]=1;
		for(int i=1;i<=18;i++) pow10[i] = 10*pow10[i-1];
		long[] a = new long[10];
		int d = 0;
		while(n>0) {
			a[(int) (n%10)]++;
			n/=10;
			d++;
		}
		TreeMap<long[],long[]> mp = new TreeMap<long[],long[]>((x,y)->{
			for(int i=0;i<10;i++) if(x[i]!=y[i]) return Long.compare(x[i], y[i]);
			return 0;
		});
		;
		System.out.println(solve(mp,a,m,false,d)[0]);
	}

	private static long[] solve(TreeMap<long[], long[]> mp, long[] a, int m, boolean useZero, int d) {
		if(mp.containsKey(a)) return mp.get(a);
		if(d==0) {
			long[] qret = new long[m];
			qret[0]=1;
			mp.put(a, qret);
			return qret;
		}
		long[] ret = new long[m];
		for(int i=0;i<10;i++) {
			if(i==0 && !useZero) continue;
			if(a[i]>0) {
				a[i]--;
				long[] f = solve(mp,Arrays.copyOf(a, a.length),m,true,d-1);
				a[i]++;
				int s = (int) ((pow10[d-1]*i)%m);
				for(int j=0;j<m;j++) ret[(j+s)%m] += f[j];
			}
		}
		mp.put(a, ret);
		return ret;
	}

}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;

public class A {
	static char [] c;
	static int n, m;
	static long [][] memo;
	static long dp(int z, int mod, int msk){
		if(msk == 0)
			return mod == 0?1:0;
		if(memo[mod][msk] != -1)
			return memo[mod][msk];
		long ans = 0;
		for(int i = 0; i < n; ++i){
			if((msk & (1<<i)) != 0 && (c[i] != '0' || z == 1)){
				boolean fnd = false;
				for (int j = 0; j < i; ++j) {
					if((msk & (1<<j)) != 0 && c[i] == c[j])
						fnd = true;
				}
				if(fnd)
					continue;
				ans += dp(z == 1 || c[i] != '0'?1:0, (mod*10 + c[i] - '0')%m, msk ^ (1<<i));
			}
		}
		return memo[mod][msk] = ans;
	}
	public static void main(String[] args) throws NumberFormatException, IOException {
		Scanner sc = new Scanner();
		PrintWriter out = new PrintWriter(System.out);
		c = sc.next().toCharArray();
		n = c.length;
		m = sc.nextInt();
		memo = new long[m+1][(1<<n)+1];
		for(long []i:memo)
			Arrays.fill(i, -1);
		out.println(dp(0, 0, (1<<n)-1));
		out.close();
	}

	static class Scanner {
		BufferedReader br;
		StringTokenizer st;

		public Scanner() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}

		public String next() throws IOException {
			while (st == null || !st.hasMoreTokens()) {
				st = new StringTokenizer(br.readLine());
			}
			return st.nextToken();
		}

		public int nextInt() throws NumberFormatException, IOException {
			return Integer.parseInt(next());
		}

		public long nextLong() throws NumberFormatException, IOException {
			return Long.parseLong(next());
		}
	}

}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;

/**
 * @author Don Li
 */
public class RomanNumbers {

    int n;
    int[] cnt;

    void solve() {
        char[] a = in.nextToken().toCharArray();
        int m = in.nextInt();

        n = a.length;
        cnt = new int[10];
        for (int i = 0; i < n; i++) {
            cnt[a[i] - '0']++;
        }

        int tot = 1;
        for (int i = 0; i < 10; i++) tot *= cnt[i] + 1;

        long[][] dp = new long[m][tot];
        dp[0][tot - 1] = 1;
        for (int s = tot - 1; s > 0; s--) {
            int[] rem = decode(s);
            for (int x = 0; x < m; x++) {
                if (dp[x][s] > 0) {
                    for (int d = 0; d < 10; d++) {
                        if (s == tot - 1 && d == 0 || rem[d] == 0) continue;
                        rem[d]--;
                        int ns = encode(rem);
                        dp[(x * 10 + d) % m][ns] += dp[x][s];
                        rem[d]++;
                    }
                }
            }
        }
        out.println(dp[0][0]);
    }

    int encode(int[] a) {
        int ret = 0;
        for (int i = 0; i < 10; i++) {
            ret = ret * (cnt[i] + 1) + a[i];
        }
        return ret;
    }

    int[] decode(int x) {
        int[] ret = new int[10];
        for (int i = 9; i >= 0; i--) {
            ret[i] = x % (cnt[i] + 1);
            x /= cnt[i] + 1;
        }
        return ret;
    }

    public static void main(String[] args) {
        in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
        out = new PrintWriter(System.out);
        new RomanNumbers().solve();
        out.close();
    }

    static FastScanner in;
    static PrintWriter out;

    static class FastScanner {
        BufferedReader in;
        StringTokenizer st;

        public FastScanner(BufferedReader in) {
            this.in = in;
        }

        public String nextToken() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(in.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(nextToken());
        }

        public long nextLong() {
            return Long.parseLong(nextToken());
        }

        public double nextDouble() {
            return Double.parseDouble(nextToken());
        }
    }
}

// practice with rainboy
import java.io.*;
import java.util.*;

public class CF401D extends PrintWriter {
	CF401D() { super(System.out, true); }
	Scanner sc = new Scanner(System.in);
	public static void main(String[] $) {
		CF401D o = new CF401D(); o.main(); o.flush();
	}

	void main() {
		long n = sc.nextLong();
		int m = sc.nextInt();
		int[] dd = new int[18];
		int k = 0;
		while (n > 0) {
			dd[k++] = (int) (n % 10);
			n /= 10;
		}
		long[][] dp = new long[1 << k][m];
		int used = 0;
		for (int h = 0; h < k; h++)
			if (dd[h] != 0 && (used & 1 << dd[h]) == 0) {
				used |= 1 << dd[h];
				dp[1 << h][dd[h] % m] = 1;
			}
		for (int b = 0; b < 1 << k; b++)
			for (int r = 0; r < m; r++) {
				long x = dp[b][r];
				if (x != 0) {
					used = 0;
					for (int h = 0; h < k; h++)
						if ((b & 1 << h) == 0 && (used & 1 << dd[h]) == 0) {
							used |= 1 << dd[h];
							dp[b | 1 << h][(r * 10 + dd[h]) % m] += x;
						}
				}
			}
		println(dp[(1 << k) - 1][0]);
	}
}

import java.util.Scanner;
import java.util.Arrays;

public class D{

	public static void main(String[] args){
		Scanner in = new Scanner(System.in);
		long n = in.nextLong();
		int mod = in.nextInt();
		long base[] = new long[18];
		int nLength = 0;
		//convert to base 10
		while(n > 0){
			base[nLength++] = n % 10L;
			n /= 10L;
		}
		Arrays.sort(base,0,nLength);
		//bitmask of each digit
		int numOfMask[] = new int[10];
		for(int i = 0 ; i < nLength ; i++)
			numOfMask[(int)(base[i])] |= (1 << i);
		long dp[][] = new long[1 << nLength][mod];
		for(int i = 0 ; i < (1 << nLength) ; i++)
			for(int j = 0 ; j < mod ; j++)
				dp[i][j] = -1;
		long ans = solve(true,(1 << nLength) - 1,0,mod,numOfMask,dp);
		System.out.println(ans);
	}

	private static long solve(boolean firstDigit,int mask,int modulo,int mod,int numOfMask[],long dp[][]){
		if(mask == 0){
			if(modulo == 0) return 1;
			return 0;
		}
		long res = dp[mask][modulo];
		if(res != -1) return res;
		res = 0;
		//place new digit in the end
		for(int i = 0 ; i < 10 ; i++){
			int cross = mask & numOfMask[i];
			if((i > 0 || !firstDigit) && cross > 0){
				int LSB = cross & -cross;
				res += solve(false,mask ^ LSB,(10 * modulo + i) % mod,mod,numOfMask,dp);
			}
		}
		dp[mask][modulo] = res;
		return res;
	}
}

import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;

public class D401 {

	int n, mod;
	int[] num;
	long[][] memo;

	public long dp(int mask, int curMod) {
		if(Integer.bitCount(mask) == n) return curMod == 0 ? 1 : 0;
		if(memo[curMod][mask] != -1) return memo[curMod][mask];
		long ans = 0;
		int checked = 0;
		for(int i = 0; i < n; ++i) {
			if((mask & (1 << i)) != 0) continue;
			if(num[i] == 0 && Integer.bitCount(mask) == 0) continue;
			if((checked & (1 << num[i])) != 0) continue;
			int nextmod = (curMod * 10 + num[i]) % mod;
			checked |= 1 << num[i];
			ans += dp(mask | (1 << i), nextmod);
		}
		return memo[curMod][mask] = ans;
	}

	public void solve(Scanner in, PrintWriter out) {
		char[] nn = in.next().toCharArray();
		mod = in.nextInt();

		n = nn.length;
		num = new int[n];
		for(int i = 0; i < n; ++i) {
			num[i] = nn[i] - '0';
		}

		memo = new long[mod][1<<n];
		for(long[] a : memo) Arrays.fill(a, -1);

		out.println(dp(0, 0));
	}

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		PrintWriter out = new PrintWriter(System.out);

		new D401().solve(in, out);

		in.close();
		out.close();
	}
}

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class CF401D{
    static int cntOne(int s){
        int ret = 0;
        while (s>0){
            s &= (s-1);
            ret ++;
        }
        return ret;
    }

    public static void main(String[] args){
        long[] pow10 = new long[18];
        long[] fact = new long[19];
        pow10[0] = 1;
        fact[0] = 1;
        for (int i=1; i<18; i++){
            pow10[i] = pow10[i-1]*10;
            fact[i] = fact[i-1]*i;
        }
        fact[18] = fact[17]*18;
        Scanner scn = new Scanner(System.in);
        while (scn.hasNext()){
            long x = scn.nextLong();
            int m = scn.nextInt();
            int[] cnt = new int[10];
            int n = 0;
            Arrays.fill(cnt, 0);
            while (x>0){
                int t = (int)(x%10);
                x /= 10;
                cnt[t] ++;
                n ++;
            }
            int allS = 1<<n;
            List<List<Integer>> stateList = new ArrayList<>();
            for (int i=0; i<=n-cnt[0]; i++){
                stateList.add(new ArrayList<>());
            }
            for (int s=0; s<allS; s++){
                if (cntOne(s)<stateList.size()) {
                    stateList.get(cntOne(s)).add(s);
                }
            }
            long dp[][] = new long[allS][m];
            for (int s=0; s<allS; s++){
                Arrays.fill(dp[s], 0L);
            }
            dp[0][0] = 1;
            int nowCnt = 0;
            for (int i=1; i<=9; i++){
                for (int j=1; j<=cnt[i]; j++){
                    nowCnt ++;
                    for (int p=0; p<n; p++){
                        int now = 1<<p;
                        long add = i*pow10[p];
                        for (int s : stateList.get(nowCnt-1)){
                            if ((s&now)!=0){
                                continue;
                            }
                            int newS = s|now;
                            for (int r=0; r<m; r++){
                                if (dp[s][r]==0){
                                    continue;
                                }
                                int newR = (int)((add+r)%m);
                                dp[newS][newR] += dp[s][r];
                            }
                        }
                    }
                    if (j==cnt[i]){
                        for (int s : stateList.get(nowCnt)){
                            for (int r=0; r<m; r++){
                                dp[s][r] /= fact[cnt[i]];
                            }
                        }
                    }
                }
            }
            long ans = 0L;
            for (int s : stateList.get(nowCnt)){
                if (s>=(1<<(n-1))){
                    ans += dp[s][0];
                }
            }
            System.out.println(ans);
        }
    }
}

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class CF401D{
    public static void main(String[] args){
        long[] fact = new long[19];
        fact[0] = 1;
        for (int i=1; i<19; i++){
            fact[i] = fact[i-1]*i;
        }
        Scanner scn = new Scanner(System.in);
        while (scn.hasNext()){
            String line = scn.nextLine();
            String[] tmp = line.split(" ");
            int m = Integer.parseInt(tmp[1]);
            int[] cnt = new int[10];
            int n = tmp[0].length();
            Arrays.fill(cnt, 0);
            for (int i=0; i<n; i++){
                cnt[tmp[0].charAt(i)-'0'] ++;
            }
            int allS = 1<<n;
            long[][] dp = new long[allS][m];
            for (int s=0; s<allS; s++){
                Arrays.fill(dp[s], 0);
            }
            dp[0][0] = 1;
            for (int s=0; s<allS; s++){
                for (int i=0; i<n; i++){
                    int now = tmp[0].charAt(i)-'0';
                    if ((now==0&&s==0)||(s&(1<<i))!=0){
                        continue;
                    }
                    for (int r=0; r<m; r++){
                        if (dp[s][r]>0){
                            int newS = s|(1<<i);
                            int newR = (10*r+now)%m;
                            dp[newS][newR] += dp[s][r];
                        }
                    }
                }
            }
            long ans = dp[allS-1][0];
            for (int i=0; i<=9; i++){
                ans /= fact[cnt[i]];
            }
            System.out.println(ans);
        }
    }
}

import java.util.Scanner;

public class Roman {

    public static void main(String[] args) {
        // TODO code application logic here
        String s;
        int m;
        Scanner sc=new Scanner(System.in);
        s=sc.next();
        m=sc.nextInt();
        int sz=s.length();
        int mx=1<<sz;
        long  dp[][]=new long[mx+10][110];
        dp[0][0]=1;
        long fact[]=new long[19];
        fact[0]=1;
        fact[1]=1;
        for(int i=2;i<=18;i++)
        {
            fact[i]=i*fact[i-1];
        }
        int num[]=new int[10];
        for(int i=0;i<s.length();i++)
        {
            num[s.charAt(i)-'0']++;
        }
        long prod=1;
        for(int i=0;i<10;i++)
        {
            prod*=fact[num[i]];
        }
        for(int mask=0;mask<mx;mask++)
        {
            for(int mod=0;mod<m;mod++)
            {
                for(int k=0;k<sz;k++)
                {

                  //  if((mask|(1<<k))==2&&(mod*10+s.charAt(k)-'0')%m==0)//&&(mod*10+(s.charAt(k)-'0'))==0)
                       // System.out.println(mask+" ere "+mod+" "+s.charAt(k));
                    if((mask&(1<<k))!=0)
                        continue;
                    if((mask==0)&&(s.charAt(k)-'0')==0)
                        continue;
                    dp[(mask|(1<<k))][(mod*10+(s.charAt(k)-'0'))%m]+=dp[mask][mod];
                }
            }
        }

        System.out.println(dp[mx-1][0]/prod);

    }

}

import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.Map.Entry;

public class Main{
	public static class FastReader {
		BufferedReader br;
		StringTokenizer root;

		public FastReader() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}

		String next() {
			while (root == null || !root.hasMoreTokens()) {
				try {
					root = new StringTokenizer(br.readLine());
				} catch (Exception addd) {
					addd.printStackTrace();
				}
			}
			return root.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());
		}

		double nextDouble() {
			return Double.parseDouble(next());
		}

		long nextLong() {
			return Long.parseLong(next());
		}

		String nextLine() {
			String str = "";
			try {
				str = br.readLine();
			} catch (Exception addd) {
				addd.printStackTrace();
			}
			return str;
		}
	}

	public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));

	public static FastReader sc = new FastReader();

	static int mod = (int) (1e2),m,n;
	static List<Integer>[] edges ;
	static long[][] dp ;
	static int[] a;
	static long[] pre;
	static char[] s,t;
	public static void main(String[] args) {

	 int t = 1;
	 while(t-->0) {
		 s = sc.next().toCharArray();
		 n = s.length;
		 m = sc.nextInt();

		 dp = new long[1<<n][m];
		 for(int i=0;i<dp.length;++i) {
			 Arrays.fill(dp[i], -1);
		 }
		 out.print(f(0,0));
	 }

	out.close();
}
	private static long f(int mask, int mod) {
		if(Long.bitCount(mask) == n) {
			if(mod == 0) return 1; // if all numbers are covered
			else return 0;
		}
		if(dp[mask][mod] != -1) return dp[mask][mod];
		long ans = 0;
		boolean[] set = new boolean[10];
		for(int i=0;i<s.length;++i) {
			int x = s[i]-'0';
			if(mask == 0 && x == 0) continue; // prevent leading zeroes
			if(set[x]) continue; // already used
			if((mask&(1<<i))!=0) continue; // not used
			set[x] = true;
			ans+=f(mask|(1<<i),(mod*10+x)%m);
		}
		return dp[mask][mod] = ans;
	}

}

import java.util.*;
import java.io.*;
public class Maximus1{
public static void main(String [] args)throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    StringTokenizer st = new StringTokenizer(br.readLine());
    long n = Long.parseLong(st.nextToken());
    int m = Integer.parseInt(st.nextToken());
    ArrayList<Integer> list = new ArrayList<>();
    while (n > 0) {
        int a = (int) (n % 10);
        list.add(a);
        n /= 10;
    }
    int len = list.size();
    long dp[][] = new long[(1 << len)][m];
    dp[0][0] = 1;
    for (int mask = 0; mask < (1 << len); mask++) {
        int cnt = Integer.bitCount(mask);
        for (int rem = 0; rem < m; rem++) {
            for (int j = 0; j < len; j++) {
                if ((mask & (1 << j)) > 0 || mask == 0 && list.get(j) == 0) continue;
                dp[mask | (1 << j)][(rem * 10 + list.get(j)) % m] += dp[mask][rem];
            }
        }
    }
    long ans = dp[(1 << len) - 1][0];
    int times[] = new int[10];
    for (int temp : list)
        times[temp]++;
    for (int i = 0; i < 10; i++) {
        for (int j = 1; j <= times[i]; j++)
            ans /= j;
    }
    System.out.print(ans);
}
}

import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.Comparator;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.math.BigInteger;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Árysson Cavalcanti
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        TaskD solver = new TaskD();
        solver.solve(1, in, out);
        out.close();
    }
}

class TaskD {
    long[][] dp;
    int[] value;
    int MOD;

    public void solve(int testNumber, InputReader in, OutputWriter out) {
        char[] str=in.readString().toCharArray();
        MOD=in.readInt();
        value=new int[11];
        value[0]=1;
        int[] count=new int[10];
        for (char i: str) count[i-'0']++;
        for (int i=0; i<10; i++) value[i+1]=value[i]*(count[i]+1);
        dp=new long[value[10]][MOD];
        ArrayUtils.fill(dp, -1);
        dp(arrayToInt(count));
        out.printLine(dp[arrayToInt(count)][0]);
    }

    int arrayToInt(int[] arr) {
        int ret=0;
        for (int i=0; i<10; i++) ret+=arr[i]*value[i];
        return ret;
    }

    void dp(int n) {
        if (dp[n][0]!=-1) return;
        int[] arr=intToArray(n);
        int c=0;
        for (int i: arr) c+=i;
        Arrays.fill(dp[n], 0);
        if (c==1) {
            for (int i=1; i<10; i++) if (arr[i]>0) dp[n][i%MOD]=1;
            return;
        }
        for (int i=0; i<10; i++) if (arr[i]>0) {
            dp(n-value[i]);
            for (int j=0; j<MOD; j++) dp[n][(10*j+i)%MOD]+=dp[n-value[i]][j];
        }
    }

    int[] intToArray(int n) {
        int[] ret=new int[10];
        for (int i=1; i<=10; i++) ret[i-1]=n%value[i]/value[i-1];
        return ret;
    }
}

class InputReader {

    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;
    private SpaceCharFilter filter;

    public InputReader(InputStream stream) {
        this.stream = stream;
    }

    public int read() {
        if (numChars == -1)
            throw new InputMismatchException();
        if (curChar >= numChars) {
            curChar = 0;
            try {
                numChars = stream.read(buf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (numChars <= 0)
                return -1;
        }
        return buf[curChar++];
    }

    public int readInt() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        int res = 0;
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

    public String readString() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        StringBuilder res = new StringBuilder();
        do {
            if (Character.isValidCodePoint(c))
                res.appendCodePoint(c);
            c = read();
        } while (!isSpaceChar(c));
        return res.toString();
    }

    public boolean isSpaceChar(int c) {
        if (filter != null)
            return filter.isSpaceChar(c);
        return isWhitespace(c);
    }

    public static boolean isWhitespace(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    public interface SpaceCharFilter {
        public boolean isSpaceChar(int ch);
    }
}

class OutputWriter {
    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {
        writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
    }

    public void close() {
        writer.close();
    }

    public void printLine(long i) {
        writer.println(i);
    }

}

class ArrayUtils {

    public static void fill(long[][] array, long value) {
        for (long[] row : array)
            Arrays.fill(row, value);
    }

}

import java.util.HashMap;
import java.util.Scanner;

public class cf401d {
	public static long factorial(int a) {
		long ret = 1;
		for (int i = 2; i <= a; i++)
			ret *= i;
		return ret;
	}

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);

		long n = in.nextLong();
		int m = in.nextInt();

		String[] Sdigs = ("" + n).split("");
		int[] digs = new int[Sdigs.length];
		for (int i = 0; i < digs.length; i++)
			digs[i] = Integer.parseInt(Sdigs[i]);
		long[][] dp = new long[1 << digs.length][m];

		dp[0][0] = 1;

		for (int i = 0; i < dp.length; i++) {
			for (int dig = 0; dig < digs.length; dig++) {
				if (((i >> dig) & 1) == 1)
					continue;
				if (i == 0 && digs[dig] == 0)
					continue;
				int index = i | (1 << dig);
				for (int j = 0; j < m; j++) {
					int newmod = (10 * j + digs[dig]) % m;
					dp[index][newmod] += dp[i][j];
				}
			}
		}

		long ans = dp[(1 << digs.length) - 1][0];
		HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
		for (int i : digs) {
			if (hm.containsKey(i))
				hm.put(i, hm.get(i) + 1);
			else
				hm.put(i, 1);
		}

		for (int i : hm.values())
			ans /= factorial(i);

		System.out.println(ans);

		in.close();
	}

	public static void debug(Object o) {
		System.out.println("\tDEBUG: " + o.toString().replaceAll("\n", "\n\tDEBUG: "));
	}
}

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Main{

    public static void main(String[] args) {
        solve();
    }

    static int mod, state[] = new int[11];
    static long dp[][];

    private static void solve() {
        char num[] = IN.next().toCharArray();
        int cnt[] = new int[10];
        for (int i = 0; i < num.length; i++) {
            cnt[num[i] - '0']++;
        }
        state[0] = 1;
        for (int i = 1; i <= 10; i++) {
            state[i] = state[i - 1] * (cnt[i - 1] + 1);
        }
        dp = new long[mod = IN.nextInt()][state[10] + 1];
        for (long tmp[] : dp) {
            Arrays.fill(tmp, -1);
        }
        System.out.println(dp(num.length - 1, 0, state[10], num, true));
    }

    public static long dp(int pos, int cur, int mask, char num[], boolean leadZero) {
        if (pos < 0) {
            return cur == 0 ? 1 : 0;
        }
        if (dp[cur][mask] != -1) {
            return dp[cur][mask];
        }
        long res = 0;
        int t, seen = 0;
        for (int i = pos; i >= 0; i--) {
            t = num[i] - '0';
            if (leadZero && t == 0 || (seen & (1 << t)) != 0) {
                continue;
            }
            seen |= (1 << t);
            swap(num, pos, i);
            res += dp(pos - 1, (cur * 10 + t) % mod, mask - state[t], num, false);
            swap(num, pos, i);
        }
        return dp[cur][mask] = res;
    }

    public static void swap(char num[], int i, int j) {
        char tmp = num[i];
        num[i] = num[j];
        num[j] = tmp;
    }

    static class IN {

        private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in), 65535);
        private static StringTokenizer st = null;

        public static String next() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (Exception e) {
                    break;
                }
            }
            return st.nextToken();
        }

        public static int nextInt() {
            return Integer.valueOf(next());
        }
    }
}

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Collections;
import java.io.InputStream;
import java.util.ArrayList;
/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author Alex
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        TaskD solver = new TaskD();
        solver.solve(1, in, out);
        out.close();
    }
    static class TaskD {
        int[] a;
        int m;
        long[][] mem;
        int[] powers10;
        long DONE;
        long[] dp(int used) {
            if (used == DONE) {
                long[] res = new long[m];
                res[0] = 1;
                return res;
            }
            if (mem[used] != null) return mem[used];
            int index = Integer.bitCount(used);
            long[] res = new long[m];
            for (int pos = 0; pos < a.length; pos++) {
                if (index == 0 && a[pos] == 0) continue;
                if (((used >> pos) & 1) != 0) continue;
                long[] get = dp(used | (1 << pos));
                int curval = powers10[a.length - index - 1];
                for (int mod = 0; mod < get.length; mod++) {
                    res[(curval * a[pos] + mod) % m] += get[mod];
                }
            }
            return mem[used] = res;
        }
        public void solve(int testNumber, InputReader in, OutputWriter out) {
            long n = in.readLong();
            m = in.readInt();
            a = toArray(n);
            Arrays.sort(a);
            DONE = (1 << a.length) - 1;
            powers10 = new int[a.length];
            powers10[0] = 1 % m;
            for (int i = 1; i < powers10.length; i++) {
                powers10[i] = powers10[i - 1] * 10;
                powers10[i] %= m;
            }
            mem = new long[1 << a.length][];
            long[] res = dp(0);
            long divisor = 1;
            int[] count = new int[10];
            for (int val : a) count[val]++;
            for (int c : count) divisor *= IntegerUtils.factorial(c);
            out.printLine(res[0] / divisor);
        }
        private int[] toArray(long n) {
            ArrayList<Integer> al = new ArrayList<>();
            while (n > 0) {
                int last = (int) (n % 10);
                al.add(last);
                n /= 10;
            }
            Collections.reverse(al);
            int[] res = new int[al.size()];
            for (int i = 0; i < res.length; i++) res[i] = al.get(i);
            return res;
        }
    }
    static class OutputWriter {
        private final PrintWriter writer;
        public OutputWriter(OutputStream outputStream) {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }
        public OutputWriter(Writer writer) {
            this.writer = new PrintWriter(writer);
        }
        public void close() {
            writer.close();
        }
        public void printLine(long i) {
            writer.println(i);
        }
    }
    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private InputReader.SpaceCharFilter filter;
        public InputReader(InputStream stream) {
            this.stream = stream;
        }
        public int read() {
            if (numChars == -1)
                throw new InputMismatchException();
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }
        public int readInt() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }
        public long readLong() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }
        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return isWhitespace(c);
        }
        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }
        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
    }
    static class IntegerUtils {
        public static long factorial(int n) {
            long result = 1;
            for (int i = 2; i <= n; i++)
                result *= i;
            return result;
        }
    }
}

import java.io.*;
import java.lang.*;
import java.util.*;

public class Main {

  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    PrintWriter out = new PrintWriter(System.out);
    new Task().solve(scanner, out);
    scanner.close();
    out.close();
  }
}

class Task {

  public void solve(Scanner in, PrintWriter out) {
    String bigNumber = in.next();
    int mod = in.nextInt();
    int n = bigNumber.length();
    int maxMask = (1 << n) - 1;
    double dp[][] = new double[maxMask + 1][mod];
    for (int k = 0; k < n; k++) {
      int bit = 1 << k;
      if ('0' != bigNumber.charAt(k))
        dp[bit][(bigNumber.charAt(k) - '0') % mod] = 1;
    }
    for (int i = 0; i < maxMask; i++) {
      for (int j =0; j < mod; j++) {
        for (int k = 0; k < n; k++) {
          int bit = 1 << k;
          if (0 == (i & bit)) {
            dp[i | bit][(j * 10 + (bigNumber.charAt(k) - '0')) % mod] += dp[i][j];
          }
        }
      }
    }
    int[] count = new int[10];
    for (int i =0; i < n; i++) {
      count[bigNumber.charAt(i) - '0']++;
    }
    double result = dp[maxMask][0];
    for (int i=0; i < 10; i++) {
      for (int j=1; j <= count[i]; j++) {
        result = result / j;
      }
    }
    out.println((int) result);
  }
}

import java.io.*;
import java.lang.*;
import java.util.*;

public class Main {

  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    PrintWriter out = new PrintWriter(System.out);
    new Task().solve(scanner, out);
    scanner.close();
    out.close();
  }
}

class Task {

  public void solve(Scanner in, PrintWriter out) {
    String bigNumber = in.next();
    int mod = in.nextInt();
    int n = bigNumber.length();
    int maxMask = (1 << n) - 1;
    int dp[][] = new int[maxMask + 1][mod];

    for (int k = 0; k < n; k++) {
      int bit = 1 << k;
      if ('0' != bigNumber.charAt(k))
        dp[bit][(bigNumber.charAt(k) - '0') % mod] = 1;
    }
    for (int i = 0; i < maxMask; i++) {
      for (int j =0; j < mod; j++) {
        for (int k = 0; k < n; k++) {
          int bit = 1 << k;
          if (0 == (i & bit)) {
            dp[i | bit][(j * 10 + (bigNumber.charAt(k) - '0')) % mod] += dp[i][j];
          }
        }
      }
    }
    int[] count = new int[10];
    for (int i =0; i < n; i++) {
      count[bigNumber.charAt(i) - '0']++;
    }
    int result = dp[maxMask][0];
    for (int i=0; i < 10; i++) {
      for (int j=1; j <= count[i]; j++) {
        result = result / j;
      }
    }
    out.println(result);
  }
}

import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.text.*;

public class cf401D {

    static BufferedReader br;
    static Scanner sc;
    static PrintWriter out;

    public static void initA() {
        try {
            br = new BufferedReader(new InputStreamReader(System.in));
            sc = new Scanner(System.in);
            out = new PrintWriter(System.out);
        } catch (Exception e) {
        }
    }

    static boolean next_permutation(Integer[] p) {
        for (int a = p.length - 2; a >= 0; --a) {
            if (p[a] < p[a + 1]) {
                for (int b = p.length - 1;; --b) {
                    if (p[b] > p[a]) {
                        int t = p[a];
                        p[a] = p[b];
                        p[b] = t;
                        for (++a, b = p.length - 1; a < b; ++a, --b) {
                            t = p[a];
                            p[a] = p[b];
                            p[b] = t;
                        }
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public static String getString() {
        try {
            return br.readLine();
        } catch (Exception e) {
        }
        return "";
    }

    public static Integer getInt() {
        try {
            return Integer.parseInt(br.readLine());
        } catch (Exception e) {
        }
        return 0;
    }

    public static Integer[] getIntArr() {
        try {
            StringTokenizer temp = new StringTokenizer(br.readLine());
            int n = temp.countTokens();
            Integer temp2[] = new Integer[n];
            for (int i = 0; i < n; i++) {
                temp2[i] = Integer.parseInt(temp.nextToken());
            }
            return temp2;
        } catch (Exception e) {
        }
        return null;
    }

    public static Long[] getLongArr() {
        try {
            StringTokenizer temp = new StringTokenizer(br.readLine());
            int n = temp.countTokens();
            Long temp2[] = new Long[n];
            for (int i = 0; i < n; i++) {
                temp2[i] = Long.parseLong(temp.nextToken());
            }
            return temp2;
        } catch (Exception e) {
        }
        return null;
    }

    public static String[] getStringArr() {
        try {
            StringTokenizer temp = new StringTokenizer(br.readLine());
            int n = temp.countTokens();
            String temp2[] = new String[n];
            for (int i = 0; i < n; i++) {
                temp2[i] = (temp.nextToken());
            }
            return temp2;
        } catch (Exception e) {
        }
        return null;
    }

    public static void print(Object a) {
        System.out.println(a);
    }

    public static void print(String s, Object... a) {
        System.out.printf(s, a);
    }

    public static int nextInt() {
        return sc.nextInt();
    }

    public static double nextDouble() {
        return sc.nextDouble();
    }

    public static void main(String[] ar) {
        initA();
        cf401D c = new cf401D();
        c.solve();
        out.flush();
    }
    int inp[] = new int[25];
    int n;
    short moder;

    void solve() {
        String in[] = getStringArr();
        char cb[] = in[0].toCharArray();
        n = cb.length;
        int ct[] = new int[10];
        for (int i = 0; i < n; i++) {
            inp[i] = cb[i] - '0';
            ct[inp[i]]++;
        }

        moder = Short.valueOf(in[1]);

        //print(100 * 100 * (1<<18) * 20);

        int end = (1 << (n));
        //print(end+" "+Integer.toString(end,2));
        long bef[][] = new long[end][100];
        bef[0][0] = 1;
        int bit[] = new int[end];
        for (int i = 0; i < end; i++) {
            int num =  0;
            int tv = i;
            while(tv > 0){
                if(tv%2==1){
                    num++;
                }
                tv/=2;
            }

            bit[i] = num;
        }
        for (int i = 1; i <= n; i++) {

            for (int k = 0; k < end; k++) {
                if(bit[k]!=i-1)continue;
                for (int j = 0; j < moder; j++) {

                    if (bef[k][j] > 0) {
                        for (int l = 0; l < n; l++) {
                            if ((k & (1 << l)) == 0) {
                                if (i == 1 && inp[l] == 0) {
                                    continue;
                                }
                                int nv = (j * 10 + inp[l]) % moder;
                                int nb = k | (1 << l);
                                //print("SEBELUM ERROR" + nv+" "+nb);
                                bef[nb][nv] += bef[k][j];
                                //print(nv + " " + Integer.toString(nb, 2) + " = " + bef[nb][nv]);
                            }
                        }
                    }
                }
            }

        }
        long ou = bef[end - 1][0];
        //print(ou);
        for (int i = 0; i < 10; i++) {
            ou /= fact(ct[i]);
        }
        print(ou);

    }

    int fact(int n) {
        if (n <= 1) {
            return 1;
        }
        return fact(n - 1) * n;
    }
}

import java.io.InputStreamReader;
import java.io.IOException;
import java.util.InputMismatchException;
import java.io.PrintStream;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Nipuna Samarasekara
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		FastScanner in = new FastScanner(inputStream);
		FastPrinter out = new FastPrinter(outputStream);
		TaskD solver = new TaskD();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskD {
   /////////////////////////////////////////////////////////////
    public void solve(int testNumber, FastScanner in, FastPrinter out) {
    int n=in.nextInt(),m=in.nextInt();
        String S=""+n;
        int len=S.length();
     long[][] dp= new long[(1<<len)+1][m+1];
      dp[0][0]=1;
      int[]  pow2= new int[30];
        pow2[0]=1;
        for (int i = 1; i < 30; i++) {
            pow2[i]=2*pow2[i-1];
        }
     long[] pow10= new long[30];
        pow10[0]=1;
        for (int i = 1; i < 30; i++) {
            pow10[i]=(pow10[i-1]*10)%m;
        }
        for (int i = 0; i < len; i++) {
            int cur=(int)S.charAt(i)-(int)'0';
            for (int j = 0; j <= (1<<len) ; j++) {
               if(Integer.bitCount(j)==i)
                for (int k = 0; k < m; k++) {
                   if(dp[j][k]!=0){
                       for (int l = 0; l < len; l++) {
                         if(cur==0&&l==0)continue;
                           if((j&pow2[l])==0) {
                            int newj=j|pow2[l],newk= (int)((k+pow10[len-1-l]*cur)%m);
                            dp[newj][newk]+=dp[j][k];

                           }
                       }

                   }

                }
            }
        }
    long ans=  dp[(1<<len)-1][0];
        int[] aa= new int[10];
        for (int i = 0; i < len; i++) {
            aa[(int)S.charAt(i)-(int)'0']++;
        }
      long[] fact= new long[20];
        fact[0]=1;
        for (int i = 1; i < 20; i++) {
            fact[i]=i*fact[i-1];
        }
        for (int i = 0; i < 10; i++) {
            if(aa[i]>1)ans/=fact[aa[i]];
        }
        out.println(ans);

    }
}

class FastScanner extends BufferedReader {

    public FastScanner(InputStream is) {
        super(new InputStreamReader(is));
    }

    public int read() {
        try {
            int ret = super.read();
//            if (isEOF && ret < 0) {
//                throw new InputMismatchException();
//            }
//            isEOF = ret == -1;
            return ret;
        } catch (IOException e) {
            throw new InputMismatchException();
        }
    }

    static boolean isWhiteSpace(int c) {
        return c >= 0 && c <= 32;
    }

    public int nextInt() {
        int c = read();
        while (isWhiteSpace(c)) {
            c = read();
        }
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        int ret = 0;
        while (c >= 0 && !isWhiteSpace(c)) {
            if (c < '0' || c > '9') {
                throw new NumberFormatException("digit expected " + (char) c
                        + " found");
            }
            ret = ret * 10 + c - '0';
            c = read();
        }
        return ret * sgn;
    }

    public String readLine() {
        try {
            return super.readLine();
        } catch (IOException e) {
            return null;
        }
    }

    }

class FastPrinter extends PrintWriter {

    public FastPrinter(OutputStream out) {
        super(out);
    }

    public FastPrinter(Writer out) {
        super(out);
    }

}

import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;

public class D {

	static Scanner sc = new Scanner(System.in);
	static PrintWriter out = new PrintWriter(System.out);

	static void exit() {
		sc.close();
		out.close();
		System.exit(0);
	}
	static int [] digits;
	static int m;
	public static void main(String[] args) {
		char [] n = sc.next().toCharArray();
		digits = new int [n.length];
		for(int i = 0; i < n.length; i++) digits[i] = n[i] - '0';
		m = sc.nextInt();
		int mask = (1 << digits.length) - 1;
		dp = new int [mask+1][m];
		for(int i = 0; i < dp.length; i++) Arrays.fill(dp[i], -1);

		out.println(dp(mask, 0));
		exit();
	}
	static int dp [][];
	static int dp(int mask, int re) {
		if(dp[mask][re] > -1) return dp[mask][re];
		if(mask == 0) {
			if(re == 0) {
				dp[mask][re] = 1;
			} else {
				dp[mask][re] = 0;
			}
			return dp[mask][re];
		}
		if(all_zero_digits(mask)) {
			dp[mask][re] = 0;
			return dp[mask][re];
		}
		boolean visited [] = new boolean [10];
		Arrays.fill(visited, false);
		Arrays.fill(dp[mask], 0);
		for(int i = 0; i < digits.length; i++) {
			if((mask & (1<<i)) > 0) {
				if(visited[digits[i]]) continue;
				visited[digits[i]] = true;
				int pre_mask = mask - (1<<i);
				for(int j = 0; j < m; j++) {
					dp[mask][ (j*10 + digits[i]) % m] += dp(pre_mask, j);
				}
			}
		}
		return dp[mask][re];
	}
	static boolean all_zero_digits(int mask) {
		for(int i = 0; i < digits.length; i++) {
			if((mask & (1<<i)) > 0) {
				if(digits[i] > 0) return false;
			}
		}
		return true;
	}
}

import java.util.*;
import java.io.*;

import static java.lang.Math.*;

public class Main {
    FastIO io;

    long n;
    int kp;
    int m;

    Map<Item, Long> d = new HashMap<Item, Long>();

    class Item {
        int[] k;
        int p;
        int mod;

        Item(int[] k) {
            this.k = k;
            p = -1;
            mod = 0;
        }

        Item(int[] k, int x, int p, int mod) {
            this.k = Arrays.copyOf(k, k.length);
            this.k[x]--;
            this.p = p + 1;
            this.mod = (int) ((x * (1L << this.p) + mod) % m);
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            Item item = (Item) o;

            if (mod != item.mod) return false;
            if (p != item.p) return false;
            if (!Arrays.equals(k, item.k)) return false;

            return true;
        }

        @Override
        public int hashCode() {
            int result = Arrays.hashCode(k);
            result = 31 * result + p;
            result = 31 * result + mod;
            return result;
        }
    }

    long get(Item x) {
        Long res = d.get(x);
        if (res != null) {
            return res;
        }
        res = 0L;
        boolean nz = false;
        for (int i = 1; i <= 9; i++) {
            if (x.k[i] != 0) {
                nz = true;
                break;
            }
        }
        if (!nz && x.k[0] != 0) {
            d.put(x, 0L);
            return 0;
        }
        if (!nz && x.mod == 0) {
            d.put(x, 1L);
            return 1;
        }
        if (!nz) {
            d.put(x, 0L);
            return 0;
        }
        for (int i = 0; i <= 9; i++) {
            if (x.k[i] != 0) {
                Item y = new Item(x.k, i, x.p, x.mod);
                res += get(y);
            }
        }
        d.put(x, res);
        return res;
    }

    // File names!!!

    void solve() throws IOException {
        n = io.nextLong();
        kp = Long.toString(n).length();
        m = io.nextInt();
        int[] k = new int[10];
        while (n > 0) {
            k[(int) (n % 10)]++;
            n /= 10;
        }
        Item t = new Item(k);
        io.println(get(t));
    }

    void run() {
        try {
            io = new FastIO();
            solve();
            io.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(abs(-1));
        }
    }

    public static void main(String[] args) {
        try {
            Locale.setDefault(Locale.US);
        } catch (Exception ignore) {
        }
        new Main().run();
    }

    class FastIO extends PrintWriter {
        private BufferedReader in;
        private StringTokenizer stok;

        FastIO() {
            super(System.out);
            in = new BufferedReader(new InputStreamReader(System.in));
        }

        FastIO(String s) throws FileNotFoundException {
            super("".equals(s) ? "output.txt" : s + ".out");
            in = new BufferedReader(new FileReader("".equals(s) ? "input.txt" : s + ".in"));
        }

        public void close() {
            super.close();
            try {
                in.close();
            } catch (IOException ignored) {
            }
        }

        String next() {
            while (stok == null || !stok.hasMoreTokens()) {
                try {
                    stok = new StringTokenizer(in.readLine());
                } catch (Exception e) {
                    return null;
                }
            }
            return stok.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }

        String nextLine() {
            try {
                return in.readLine();
            } catch (IOException e) {
                return null;
            }
        }

        char[] nextCharArray() {
            return next().toCharArray();
        }

    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.concurrent.PriorityBlockingQueue;

public class aa {

	public static class node implements Comparable<node> {
		int x;
		int y;

		node(int x, int y) {
			this.x = x;
			this.y = y;
		}

		@Override
		public int compareTo(node o) {
			if (o.x < x)
				return 1;
			else if (o.x > x)
				return -1;
			else if (o.y < y)
				return 1;
			else
				return -1;
		}
	}

	public static int mod;
	public static String num;

	public static long dp[][];
	public static int n;

	public static long getFact() {
		int a[] = new int[10];
		for (int i = 0; i < num.length(); i++) {
			a[num.charAt(i) - 48]++;
		}
		long fact = 1;
		for (int i = 0; i < 10; i++) {
			if (a[i] != 0)
				fact *= fact(a[i]);
		}
		return fact;
	}

	public static long fact(int n) {
		long ans = 1;
		for (int i = 1; i <= n; i++) {
			ans *= i;
		}
		return ans;
	}
	public static long f;
	public static long solve(int mask, int number, int count, long dig) {

		if (mask == (1 << n) - 1) {
			if ( number == 0) {

				return 1;
			}
			return 0;

		}
		if (dp[mask][number] != -1)
			return dp[mask][number];
		int a = 0;
		for (int i = 0; i < n; i++) {
			if (count == 0 && num.charAt(i) == '0') {
			} else {
				if ((mask & (1 << i)) == 0) {
					a += solve(mask | (1 << i), ((number % mod * 10 % mod)
							% mod + (num.charAt(i) - 48) % mod)
							% mod, count + 1, dig * 10 + (num.charAt(i) - 48));
				}
			}
		}
		dp[mask][number] = a;
		return a;

	}

	public static void main(String[] args) throws IOException {

		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
		StringBuilder q = new StringBuilder();
		String y[] = in.readLine().trim().split(" ");
		num = y[0];
		mod = Integer.parseInt(y[1]);
		n = num.length();
		dp = new long[1 << n +1][mod];
		for (int i = 0; i < (1 << n + 1); i++) {
			for (int j = 0; j < mod; j++) {
				dp[i][j] = -1;
			}
		}
		f=getFact();
		out.println(solve(0, 0, 0, 0)/f);

		out.print(q);
		out.close();

	}
}

import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.HashSet;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		PrintWriter out = new PrintWriter(outputStream);
		TaskD solver = new TaskD();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskD {
    long dp[][];
    char no[];
    int m;
    int len;
    public void solve(int testNumber, InputReader in, PrintWriter out) {
        no = (in.readInt() + "").toCharArray();
        len = no.length;
        m = in.readInt();
        dp = new long[1 << 18][100];
        for (long[] a : dp) Arrays.fill(a, -1);
        out.println(go(0, 0));
    }
    long go(int mask, int mod) {
        if (mask == (1 << len) - 1){
            if (mod == 0) return 1;
            return 0;
        }
        HashSet<Character> hs = new HashSet<Character>();
        if (dp[mask][mod] != -1) return dp[mask][mod];
        long ans = 0;
        for (int i = 0; i < len; i++) {
            if (((mask >> i) & 1) != 0) continue;
            if (mask == 0 && no[i] == '0') continue;
            if (hs.contains(no[i])) continue;
            hs.add(no[i]);
            ans += go(mask | (1 << i), ((mod * 10) + no[i] - '0') % m);
        }
        return dp[mask][mod] = ans;
    }
}

class InputReader {

        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream) {
                this.stream = stream;
        }

        public int read() {
                if (numChars == -1)
                        throw new InputMismatchException();
                if (curChar >= numChars) {
                        curChar = 0;
                        try {
                                numChars = stream.read(buf);
                        } catch (IOException e) {
                                throw new InputMismatchException();
                        }
                        if (numChars <= 0)
                                return -1;
                }
                return buf[curChar++];
        }

        public int readInt() {
                int c = read();
                while (isSpaceChar(c))
                        c = read();
                int sgn = 1;
                if (c == '-') {
                        sgn = -1;
                        c = read();
                }
                int res = 0;
                do {
                        if (c < '0' || c > '9')
                                throw new InputMismatchException();
                        res *= 10;
                        res += c - '0';
                        c = read();
                } while (!isSpaceChar(c));
                return res * sgn;
        }

        public boolean isSpaceChar(int c) {
                if (filter != null)
                        return filter.isSpaceChar(c);
                return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
                return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
                public boolean isSpaceChar(int ch);
        }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;

public class _D {
    static long dp[][],ten[];
    static int len,arr[],m;
    static long solve(int index, int mod,int mask){
        if(index == len){
            if(mod%m==0){
                return 1;
            }
            return 0;
        }
        else if(dp[mod][mask]!=-1){
            return dp[mod][mask];
        }
        else {
            long way =0;
            int red[] = new int [10];
            for(int i= 0;i<len;i++){
                if((mask&(1<<i))==0){
                    if((index==0&&arr[i]==0)||red[arr[i]]==1)
                        continue;
                    red[arr[i]] = 1;
                    way+=solve(index+1, (int) (mod+(arr[i]*(ten[index]%m)))%m, mask|(1<<i));
                }
            }
            return   way;
        }
    }
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(System.out);
        StringTokenizer st = new StringTokenizer(in.readLine());
        long n = Long.parseLong(st.nextToken());
        ten = new long [19];
        ten[0] = 1;
        for(int i=1;i<ten.length;i++)
            ten[i]=ten[i-1]*10;
        m = Integer.parseInt(st.nextToken());
        long temp = n;
        while(temp>0){
            temp/=10;
            len++;
        }
        arr= new int[len];
        int i = 0;
        int digit[] = new int [10];
        while(n>0){
            arr[i] = (int) (n%10);
            digit[arr[i]]++;
            i++;
            n/=10;
        }
        dp = new long [101][1<<18];
        for(i = 0;i<dp.length;i++)
            Arrays.fill(dp[i], -1);
        out.println(solve(0,0, 0));
        in.close();
        out.close();
    }

}

import java.io.*;
import java.math.*;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;

public class Main {

    InputReader in;
    PrintWriter out;

    void run(){
        /*try {
            out = new PrintWriter(new FileOutputStream("output.txt"));
            in = new InputReader(new FileInputStream("input.txt"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }*/
        out = new PrintWriter(new OutputStreamWriter(System.out));
        in = new InputReader(System.in);
        solve();
        out.flush();
    }

    public static void main(String[] args){
        new Main().run();
    }

    int[] digits;
    int m;
    int[][] dp;
    int full;

    int divisible(int remainder, int taken) {
        if(taken == full) {
            return (remainder == 0 ? 1 : 0);
        }
        if(dp[remainder][taken] != -1)
            return dp[remainder][taken];
        int res = 0;
        for(int i = 0; i < digits.length; i++) {
            if((taken & (1 << i)) == 0) {
                if(taken == 0 && digits[i] == 0)
                    continue;
                if(i > 0 && digits[i-1] == digits[i] && (taken & (1 << (i-1))) != 0)
                    continue;
                res += divisible((remainder * 10 + digits[i]) % m, taken | (1 << i));
            }
        }
        return dp[remainder][taken] = res;
    }

    void solve() {
        String s = in.ns();
        m = in.ni();
        digits = new int[s.length()];
        for(int i = 0; i < digits.length; i++)
            digits[i] = s.charAt(i) - '0';
        dp = new int[101][1<<digits.length];
        for(int[] x : dp)
            Arrays.fill(x, -1);
        Arrays.sort(digits);
        full = (1 << digits.length) - 1;
        out.println(divisible(0, 0));
    }

    class InputReader {
        private boolean finished = false;
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1)
                throw new InputMismatchException();
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int peek() {
            if (numChars == -1)
                return -1;
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    return -1;
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar];
        }

        public int ni() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public long nl() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public String ns() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return isWhitespace(c);
        }

        public boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        private String readLine0() {
            StringBuilder buf = new StringBuilder();
            int c = read();
            while (c != '\n' && c != -1) {
                if (c != '\r')
                    buf.appendCodePoint(c);
                c = read();
            }
            return buf.toString();
        }

        public String readLine() {
            String s = readLine0();
            while (s.trim().length() == 0)
                s = readLine0();
            return s;
        }

        public String readLine(boolean ignoreEmptyLines) {
            if (ignoreEmptyLines)
                return readLine();
            else
                return readLine0();
        }

        public BigInteger readBigInteger() {
            try {
                return new BigInteger(ns());
            } catch (NumberFormatException e) {
                throw new InputMismatchException();
            }
        }

        public char readCharacter() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            return (char) c;
        }

        public double readDouble() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            double res = 0;
            while (!isSpaceChar(c) && c != '.') {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, ni());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            if (c == '.') {
                c = read();
                double m = 1;
                while (!isSpaceChar(c)) {
                    if (c == 'e' || c == 'E')
                        return res * Math.pow(10, ni());
                    if (c < '0' || c > '9')
                        throw new InputMismatchException();
                    m /= 10;
                    res += (c - '0') * m;
                    c = read();
                }
            }
            return res * sgn;
        }

        public boolean eof() {
            int value;
            while (isSpaceChar(value = peek()) && value != -1)
                read();
            return value == -1;
        }

        public String next() {
            return ns();
        }

        public SpaceCharFilter getFilter() {
            return filter;
        }

        public void setFilter(SpaceCharFilter filter) {
            this.filter = filter;
        }
    }
    public interface SpaceCharFilter {
        public boolean isSpaceChar(int ch);
    }

}

import java.io.*;
import java.math.*;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;

public class Main {

    InputReader in;
    PrintWriter out;

    void run(){
        /*try {
            out = new PrintWriter(new FileOutputStream("output.txt"));
            in = new InputReader(new FileInputStream("input.txt"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }*/
        out = new PrintWriter(new OutputStreamWriter(System.out));
        in = new InputReader(System.in);
        solve();
        out.flush();
    }

    public static void main(String[] args){
        new Main().run();
    }

    int[] digits;
    int m;
    int[][] dp;
    int full;

    int divisible(int remainder, int taken) {
        if(taken == full) {
            return (remainder == 0 ? 1 : 0);
        }
        if(dp[remainder][taken] != -1)
            return dp[remainder][taken];
        int res = 0;
        for(int i = 0; i < digits.length; i++) {
            if((taken & (1 << i)) == 0) {
                if(taken == 0 && digits[i] == 0)
                    continue;
                if(i > 0 && digits[i-1] == digits[i] && (taken & (1 << (i-1))) != 0)
                    continue;
                res += divisible((remainder * 10 + digits[i]) % m, taken | (1 << i));
            }
        }
        return dp[remainder][taken] = res;
    }

    void solve() {
        String s = in.ns();
        m = in.ni();
        digits = new int[s.length()];
        for(int i = 0; i < digits.length; i++)
            digits[i] = s.charAt(i) - '0';
        dp = new int[101][1<<digits.length];
        for(int[] x : dp)
            Arrays.fill(x, -1);
        Arrays.sort(digits);
        full = (1 << digits.length) - 1;

for(int k = 0; k < 10; k++)
        out.println(divisible(0, 0));
    }

    class InputReader {
        private boolean finished = false;
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1)
                throw new InputMismatchException();
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int peek() {
            if (numChars == -1)
                return -1;
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    return -1;
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar];
        }

        public int ni() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public long nl() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public String ns() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return isWhitespace(c);
        }

        public boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        private String readLine0() {
            StringBuilder buf = new StringBuilder();
            int c = read();
            while (c != '\n' && c != -1) {
                if (c != '\r')
                    buf.appendCodePoint(c);
                c = read();
            }
            return buf.toString();
        }

        public String readLine() {
            String s = readLine0();
            while (s.trim().length() == 0)
                s = readLine0();
            return s;
        }

        public String readLine(boolean ignoreEmptyLines) {
            if (ignoreEmptyLines)
                return readLine();
            else
                return readLine0();
        }

        public BigInteger readBigInteger() {
            try {
                return new BigInteger(ns());
            } catch (NumberFormatException e) {
                throw new InputMismatchException();
            }
        }

        public char readCharacter() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            return (char) c;
        }

        public double readDouble() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            double res = 0;
            while (!isSpaceChar(c) && c != '.') {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, ni());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            if (c == '.') {
                c = read();
                double m = 1;
                while (!isSpaceChar(c)) {
                    if (c == 'e' || c == 'E')
                        return res * Math.pow(10, ni());
                    if (c < '0' || c > '9')
                        throw new InputMismatchException();
                    m /= 10;
                    res += (c - '0') * m;
                    c = read();
                }
            }
            return res * sgn;
        }

        public boolean eof() {
            int value;
            while (isSpaceChar(value = peek()) && value != -1)
                read();
            return value == -1;
        }

        public String next() {
            return ns();
        }

        public SpaceCharFilter getFilter() {
            return filter;
        }

        public void setFilter(SpaceCharFilter filter) {
            this.filter = filter;
        }
    }
    public interface SpaceCharFilter {
        public boolean isSpaceChar(int ch);
    }

}

import java.io.*;
import java.math.*;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;

public class Main {

    InputReader in;
    PrintWriter out;

    void run(){
        /*try {
            out = new PrintWriter(new FileOutputStream("output.txt"));
            in = new InputReader(new FileInputStream("input.txt"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }*/
        out = new PrintWriter(new OutputStreamWriter(System.out));
        in = new InputReader(System.in);
        solve();
        out.flush();
    }

    public static void main(String[] args){
        new Main().run();
    }

    int[] digits;
    int m;
    int[][] dp;
    int full;

    int divisible(int remainder, int taken) {
        if(taken == full) {
            return (remainder == 0 ? 1 : 0);
        }
        if(dp[remainder][taken] != -1)
            return dp[remainder][taken];
        int res = 0;
        for(int i = 0; i < digits.length; i++) {
            if((taken & (1 << i)) == 0) {
                if(taken == 0 && digits[i] == 0)
                    continue;
                if(i > 0 && digits[i-1] == digits[i] && (taken & (1 << (i-1))) != 0)
                    continue;
                res += divisible((remainder * 10 + digits[i]) % m, taken | (1 << i));
            }
        }
        return dp[remainder][taken] = res;
    }

    void solve() {
        String s = in.ns();
        m = in.ni();
        digits = new int[s.length()];
        for(int i = 0; i < digits.length; i++)
            digits[i] = s.charAt(i) - '0';
        dp = new int[101][1<<digits.length];
        for(int[] x : dp)
            Arrays.fill(x, -1);

for(int k = 0; k < 10; k++) {}
        Arrays.sort(digits);
        full = (1 << digits.length) - 1;
        out.println(divisible(0, 0));
    }

    class InputReader {
        private boolean finished = false;
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1)
                throw new InputMismatchException();
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int peek() {
            if (numChars == -1)
                return -1;
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    return -1;
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar];
        }

        public int ni() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public long nl() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            long res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public String ns() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = read();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return isWhitespace(c);
        }

        public boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        private String readLine0() {
            StringBuilder buf = new StringBuilder();
            int c = read();
            while (c != '\n' && c != -1) {
                if (c != '\r')
                    buf.appendCodePoint(c);
                c = read();
            }
            return buf.toString();
        }

        public String readLine() {
            String s = readLine0();
            while (s.trim().length() == 0)
                s = readLine0();
            return s;
        }

        public String readLine(boolean ignoreEmptyLines) {
            if (ignoreEmptyLines)
                return readLine();
            else
                return readLine0();
        }

        public BigInteger readBigInteger() {
            try {
                return new BigInteger(ns());
            } catch (NumberFormatException e) {
                throw new InputMismatchException();
            }
        }

        public char readCharacter() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            return (char) c;
        }

        public double readDouble() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            double res = 0;
            while (!isSpaceChar(c) && c != '.') {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, ni());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            if (c == '.') {
                c = read();
                double m = 1;
                while (!isSpaceChar(c)) {
                    if (c == 'e' || c == 'E')
                        return res * Math.pow(10, ni());
                    if (c < '0' || c > '9')
                        throw new InputMismatchException();
                    m /= 10;
                    res += (c - '0') * m;
                    c = read();
                }
            }
            return res * sgn;
        }

        public boolean eof() {
            int value;
            while (isSpaceChar(value = peek()) && value != -1)
                read();
            return value == -1;
        }

        public String next() {
            return ns();
        }

        public SpaceCharFilter getFilter() {
            return filter;
        }

        public void setFilter(SpaceCharFilter filter) {
            this.filter = filter;
        }
    }
    public interface SpaceCharFilter {
        public boolean isSpaceChar(int ch);
    }

}

import java.io.IOException;
import java.util.Arrays;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Mahmoud Aladdin <aladdin3>
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		PrintWriter out = new PrintWriter(outputStream);
		TaskD solver = new TaskD();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskD {
    int[] input;
    int m;

    int[][] memory = new int[(1 << 18)][10];

    public void solve(int testNumber, InputReader jin, PrintWriter jout) {
        String token = jin.token();
        m = jin.int32();

        input = new int[token.length()];
        for(int i = 0; i < token.length(); i++) {
            input[i] = token.charAt(i) - '0';
        }

        for(int[] r: memory) Arrays.fill(r, -1);

        BigInteger mask = BigInteger.ZERO;
        BigInteger curr = BigInteger.ZERO;
        int res = 0;
        for(int i = 0; i < input.length; i++) {
            if(input[i] != 0) {
                if(curr.testBit(input[i])) continue;
                curr = curr.setBit(input[i]);
                res += bt(mask.setBit(i), input[i] % m, input[i]);
            }
        }
        jout.println(res);
    }

    private long bt(BigInteger mask, int rem, long val) {
        if(mask.intValue() == (1 << input.length) - 1) {
            return rem == 0? 1: 0;
        } else {
            if(memory[mask.intValue()][rem] != -1)
                return memory[mask.intValue()][rem];
            int res = 0;
            BigInteger currMask = BigInteger.ZERO;
            for(int i = 0; i < input.length; i++) {
                if(mask.testBit(i)) continue;
                if(currMask.testBit(input[i])) continue;
                currMask = currMask.setBit(input[i]);
                res += bt(mask.setBit(i), ((rem * 10) + input[i]) % m, val * 10 + input[i]);
            }
            return memory[mask.intValue()][rem] = res;
        }
    }
}

class InputReader {
    private static final int bufferMaxLength = 1024;
    private InputStream in;
    private byte[] buffer;
    private int currentBufferSize;
    private int currentBufferTop;
    private static final String tokenizers = " \t\r\f\n";

    public InputReader(InputStream stream) {
        this.in = stream;
        buffer = new byte[bufferMaxLength];
        currentBufferSize = 0;
        currentBufferTop = 0;
    }

    private boolean refill() {
        try {
            this.currentBufferSize = this.in.read(this.buffer);
            this.currentBufferTop = 0;
        } catch(Exception e) {}
        return this.currentBufferSize > 0;
    }

    private Byte readChar() {
        if(currentBufferTop < currentBufferSize) {
            return this.buffer[this.currentBufferTop++];
        } else {
            if(!this.refill()) {
                return null;
            } else {
                return readChar();
            }
        }
    }

    public String token()  {
        StringBuffer tok = new StringBuffer();
        Byte first;
        while((first = readChar()) != null && (tokenizers.indexOf((char) first.byteValue()) != -1));
        if(first == null) return null;
        tok.append((char)first.byteValue());
        while((first = readChar()) != null && (tokenizers.indexOf((char) first.byteValue()) == -1)) {
            tok.append((char)first.byteValue());
        }
        return tok.toString();
    }

    public Integer int32() throws NumberFormatException {
        String tok = token();
        return tok == null? null : Integer.parseInt(tok);
    }

    }

import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		FastScanner in = new FastScanner(inputStream);
		PrintWriter out = new PrintWriter(outputStream);
		TaskD solver = new TaskD();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskD {
        public void solve(int testNumber, FastScanner in, PrintWriter out) {
                long n = in.nextLong();
                int m = in.nextInt();
                int[] mods = new int[18];
                mods[0] = 1;
                for (int i = 1; i < mods.length; i++)
                        mods[i] = mods[i - 1] * 10 % m;
                out.println();
                String val = Long.toString(n);
                int cnt = val.length();
                int[] digits = new int[cnt];
                for (int i = 0; i < cnt; i++)
                        digits[i] = val.charAt(i) - '0';
                long[][] dp = new long[m][1 << cnt];
                dp[0][0] = 1;
                for (int mask = 0; mask < (1 << cnt); mask++) {
                        int pos = Integer.bitCount(mask);
                        for (int curMod = 0; curMod < m; curMod++) {
                                for (int newPos = 0; newPos < cnt; newPos++) {
                                        if ((mask & (1 << newPos)) != 0)
                                                continue;
                                        if (digits[pos] == 0 && newPos == cnt - 1)
                                                continue;
                                        int newMod = (curMod + mods[newPos] * digits[pos]) % m;
                                        dp[newMod][mask | (1 << newPos)] += dp[curMod][mask];
                                }
                        }
                }
                long[] fact = new long[20];
                fact[0] = 1;
                for (int i = 1; i < 20; i++)
                        fact[i] = fact[i - 1] * i;
                int[] count = new int[10];
                for (int d : digits)
                        count[d]++;
                long res = dp[0][(1 << cnt) - 1];
                for (int d = 0; d < 10; d++)
                        res /= fact[count[d]];
                out.print(res);
        }
}

class FastScanner {
        BufferedReader reader;
        StringTokenizer tokenizer;

        public FastScanner(InputStream inputStream)  {
                reader = new BufferedReader(new InputStreamReader(inputStream));
        }

        public String nextToken() {
                while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                        String line;
                        try {
                                line = reader.readLine();
                        } catch (IOException e) {
                                return null;
                        }
                        tokenizer = new StringTokenizer(line);
                }
                return tokenizer.nextToken();
        }

        public int nextInt() {
                return Integer.parseInt(nextToken());
        }

        public long nextLong() {
                return Long.parseLong(nextToken());
        }

        }

import java.util.*;
import java.io.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
import static java.lang.Math.*;

public class D {

	int INF = 1 << 28;
	//long INF = 1L << 62;
	double EPS = 1e-10;
	ExMap[] maps;

	void run() {
		maps = new ExMap[2];
		maps[0] = new ExMap(); maps[1] = new ExMap();
		Scanner sc = new Scanner(System.in);
		String n = sc.next();int m = sc.nextInt();
		int[] ns = new int[10]; int l = n.length();
		for(int i=0;i<l;i++) ns[n.charAt(i) - '0']++;

		long[] pow = new long[10]; pow[0] = 1;
		for(int i=1;i<10;i++) pow[i] = pow[i-1] * 10;

		long ndig = 0;
		for(int i=0;i<10;i++) ndig += pow[i] * ns[i];

		long[] dp = new long[m]; dp[0] = 1;
		maps[0].put(ndig, dp);
		int x = 1;
		long[] val, tar; long key;
		for(int i=0;i<l;i++) {
			maps[x].clear();
			for(Map.Entry<Long, long[]> entry: maps[1-x].entrySet()) {
				key = entry.getKey();
				tar = entry.getValue();
				for(int j=(i==0? 1: 0);j<10;j++) if((key / pow[j]) % 10 > 0) {

					if(maps[x].containsKey(key - pow[j])) val = maps[x].get(key - pow[j]);
					else val = new long[m];
					for(int k=0;k<m;k++) val[(k*10 + j) % m] += tar[k];

					maps[x].put(key - pow[j], val);
				}
			}
			x = 1-x;
		}
		for(Map.Entry<Long, long[]> entry: maps[1-x].entrySet()) {
			tar = entry.getValue();
			long ans = tar[0];
			System.out.println(ans);
		}
	}

	class ExMap extends HashMap<Long, long[]>{}

	void debug(Object... os) {
		System.err.println(Arrays.deepToString(os));
	}

	public static void main(String[] args) {
		new D().run();
	}
}

/**
 * ******* Created  on 20/12/19 9:09 PM*******
 */

import java.io.*;
import java.util.*;

public class D401 implements Runnable {

    private static final int MAX =3* (int) (1E5 + 5);
    private static final int MOD = (int) (1E9 + 7);
    private static final long Inf = (long) (1E14 + 10);
    int[][]dp = new int[MAX][105];
    private void solve() throws IOException {
        long n = reader.nextLong();
        int m = reader.nextInt();
        int[] has =  new int[20];
        int[] cnt = new int[10];
        int id =0;
        int[] pw = new int[20];
        long[] fac = new long[20];
        while (n > 0) {
            has[id++] = (int) (n % 10L); cnt[(int) (n % 10)]++;
            n /= 10;
        }
        pw[0] = 1 % m;
        for (int i = 1; i < id; i++)
            pw[i] = 10 * pw[i - 1] % m;
        fac[0] = 1;
        for (int i = 1; i <= id; i++)
            fac[i] = fac[i - 1] * i;
        dp[0][0] =1;
        for(int i=0;i<(1<<id);i++){
            int b =0;
            for(int j=0;j<id;j++){
                if( (i&(1<<j)) >0)b++;
            }
            for(int j =0;j<m;j++)if(dp[i][j]!=0){
                for(int k =0;k<id;k++){
                    if(( !((i & (1<<k))> 0) &&(k+1< id || has[b] !=0) )) {
                        int x = (int) ((has[b]*pw[k] + j)%m);
                        dp[i | (1<<k)][x] = (dp[i | (1<<k)][x] + dp[i][j]);

                    }
                }
            }
        }
        long ans = dp[(1<<id)-1][0];
        for(int i =0;i<10;i++)
            ans /= fac[cnt[i]];
        writer.println(ans);
    }

    public static void main(String[] args) throws IOException {
        try (Input reader = new StandardInput(); PrintWriter writer = new PrintWriter(System.out)) {
            new D401().run();
        }
    }

    StandardInput reader;
    PrintWriter writer;

    @Override
    public void run() {
        try {
            reader = new StandardInput();
            writer = new PrintWriter(System.out);
            solve();
            reader.close();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    interface Input extends Closeable {
        String next() throws IOException;

        default int nextInt() throws IOException {
            return Integer.parseInt(next());
        }

        default long nextLong() throws IOException {
            return Long.parseLong(next());
        }

        default double nextDouble() throws IOException {
            return Double.parseDouble(next());
        }

        default int[] readIntArray() throws IOException {
            return readIntArray(nextInt());
        }

        default int[] readIntArray(int size) throws IOException {
            int[] array = new int[size];
            for (int i = 0; i < array.length; i++) {
                array[i] = nextInt();
            }
            return array;
        }

        default long[] readLongArray(int size) throws IOException {
            long[] array = new long[size];
            for (int i = 0; i < array.length; i++) {
                array[i] = nextLong();
            }
            return array;
        }
    }

    private static class StandardInput implements Input {
        private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        private StringTokenizer stringTokenizer;

        @Override
        public void close() throws IOException {
            reader.close();
        }

        @Override
        public String next() throws IOException {
            if (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
                stringTokenizer = new StringTokenizer(reader.readLine());
            }
            return stringTokenizer.nextToken();
        }
    }
}

/**
 * DA-IICT
 * Author : PARTH PATEL
 */
import java.io.*;
import java.math.*;
import java.util.*;

import static java.util.Arrays.fill;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;

public class D401 {

	public static int mod = 1000000007;
	static FasterScanner in = new FasterScanner();
	static PrintWriter out = new PrintWriter(System.out);
	public static int factorial(int n)
	{
		if(n==0)
			return 1;
		else
			return n*factorial(n-1);
	}
	public static void main(String[] args) {

		String s=in.nextString();
		int m=in.nextInt();
		char[] arr=s.toCharArray();
		int n=arr.length;
		long[][] dp=new long[1<<n][m];
		dp[0][0]=1;
		for(int i=0;i<(1<<n);i++)
		{
			for(int j=0;j<m;j++)
			{
				if(dp[i][j]==0)
				{
					//in mask i there is no element with mod value j=(i%m)
					continue;
				}
				for(int k=0;k<n;k++)
				{
					if((i & (1<<k))==0)
					{
						//there should not be zero initially
						if(i==0 && arr[k]=='0')
							continue;
						//kth bit is not there in mask i. So we can include it
						dp[i|(1<<k)][(j*10+arr[k]-'0')%m]+=dp[i][j];
					}
				}
			}
		}
		long answer=dp[(1<<n)-1][0];
		int[] frequency=new int[10];
		for(int i=0;i<n;i++)
		{
			frequency[arr[i]-'0']++;
		}
		for(int i=0;i<10;i++)
		{
			answer/=(factorial(frequency[i]));
		}
		out.println(answer);
		out.close();

	}

	public static long pow(long x, long n, long mod) {
		long res = 1;
		for (long p = x; n > 0; n >>= 1, p = (p * p) % mod) {
			if ((n & 1) != 0) {
				res = (res * p % mod);
			}
		}
		return res;
	}

	public static long gcd(long n1, long n2) {
		long r;
		while (n2 != 0) {
			r = n1 % n2;
			n1 = n2;
			n2 = r;
		}
		return n1;
	}

	public static long lcm(long n1, long n2) {
		long answer = (n1 * n2) / (gcd(n1, n2));
		return answer;
	}

	static class FasterScanner {
		private byte[] buf = new byte[1024];
		private int curChar;
		private int snumChars;

		public int read() {
			if (snumChars == -1)
				throw new InputMismatchException();
			if (curChar >= snumChars) {
				curChar = 0;
				try {
					snumChars = System.in.read(buf);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (snumChars <= 0)
					return -1;
			}
			return buf[curChar++];
		}

		public String nextLine() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isEndOfLine(c));
			return res.toString();
		}

		public String nextString() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			StringBuilder res = new StringBuilder();
			do {
				res.appendCodePoint(c);
				c = read();
			} while (!isSpaceChar(c));
			return res.toString();
		}

		public long nextLong() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = read();
			}
			long res = 0;
			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public int nextInt() {
			int c = read();
			while (isSpaceChar(c))
				c = read();
			int sgn = 1;
			if (c == '-') {
				sgn = -1;
				c = read();
			}
			int res = 0;
			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res *= 10;
				res += c - '0';
				c = read();
			} while (!isSpaceChar(c));
			return res * sgn;
		}

		public int[] nextIntArray(int n) {
			int[] arr = new int[n];
			for (int i = 0; i < n; i++) {
				arr[i] = nextInt();
			}
			return arr;
		}

		public long[] nextLongArray(int n) {
			long[] arr = new long[n];
			for (int i = 0; i < n; i++) {
				arr[i] = nextLong();
			}
			return arr;
		}

		private boolean isSpaceChar(int c) {
			return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
		}

		private boolean isEndOfLine(int c) {
			return c == '\n' || c == '\r' || c == -1;
		}
	}

}

import java.util.*;
import java.io.*;
import java.awt.Point;
import java.math.BigDecimal;
import java.math.BigInteger;

import static java.lang.Math.*;

// Solution is at the bottom of code

public class D implements Runnable{

	final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;

	BufferedReader in;
	OutputWriter out;
	StringTokenizer tok = new StringTokenizer("");

	public static void main(String[] args){
		new Thread(null, new D(), "", 128 * (1L << 20)).start();
	}

	/////////////////////////////////////////////////////////////////////

	void init() throws FileNotFoundException{
		Locale.setDefault(Locale.US);

		if (ONLINE_JUDGE){
			in = new BufferedReader(new InputStreamReader(System.in));
			out = new OutputWriter(System.out);
		}else{
			in = new BufferedReader(new FileReader("input.txt"));
			out = new OutputWriter("output.txt");
		}
	}

	////////////////////////////////////////////////////////////////

	long timeBegin, timeEnd;

	void time(){
		timeEnd = System.currentTimeMillis();
		System.err.println("Time = " + (timeEnd - timeBegin));
	}

	void debug(Object... objects){
		if (ONLINE_JUDGE){
			for (Object o: objects){
				System.err.println(o.toString());
			}
		}
	}

	/////////////////////////////////////////////////////////////////////

	public void run(){
		try{
			timeBegin = System.currentTimeMillis();
			Locale.setDefault(Locale.US);

			init();
			solve();

			out.close();
			time();
		}catch (Exception e){
			e.printStackTrace(System.err);
			System.exit(-1);
		}
	}

	/////////////////////////////////////////////////////////////////////

	String delim = " ";

	String readString() throws IOException{
		while(!tok.hasMoreTokens()){
			try{
				tok = new StringTokenizer(in.readLine());
			}catch (Exception e){
				return null;
			}
		}

		return tok.nextToken(delim);
	}

	String readLine() throws IOException{
		return in.readLine();
	}

	/////////////////////////////////////////////////////////////////

	final char NOT_A_SYMBOL = '\0';

	char readChar() throws IOException{
		int intValue = in.read();

		if (intValue == -1){
			return NOT_A_SYMBOL;
		}

		return (char) intValue;
	}

	char[] readCharArray() throws IOException{
		return readLine().toCharArray();
	}

	/////////////////////////////////////////////////////////////////

	int readInt() throws IOException {
		return Integer.parseInt(readString());
	}

	int[] readIntArray(int size) throws IOException {
		int[] array = new int[size];

		for (int index = 0; index < size; ++index){
			array[index] = readInt();
		}

		return array;
	}

	int[] readIntArrayWithDecrease(int size) throws IOException {
		int[] array = readIntArray(size);

		for (int i = 0; i < size; ++i) {
			array[i]--;
		}

		return array;
	}

	///////////////////////////////////////////////////////////////////

	long readLong() throws IOException{
		return Long.parseLong(readString());
	}

	long[] readLongArray(int size) throws IOException{
		long[] array = new long[size];

		for (int index = 0; index < size; ++index){
			array[index] = readLong();
		}

		return array;
	}

	////////////////////////////////////////////////////////////////////

	double readDouble() throws IOException{
		return Double.parseDouble(readString());
	}

	double[] readDoubleArray(int size) throws IOException{
		double[] array = new double[size];

		for (int index = 0; index < size; ++index){
			array[index] = readDouble();
		}

		return array;
	}

	////////////////////////////////////////////////////////////////////

	BigInteger readBigInteger() throws IOException {
		return new BigInteger(readString());
	}

	BigDecimal readBigDecimal() throws IOException {
		return new BigDecimal(readString());
	}

	/////////////////////////////////////////////////////////////////////

	Point readPoint() throws IOException{
		int x = readInt();
		int y = readInt();
		return new Point(x, y);
	}

	Point[] readPointArray(int size) throws IOException{
		Point[] array = new Point[size];

		for (int index = 0; index < size; ++index){
			array[index] = readPoint();
		}

		return array;
	}

	/////////////////////////////////////////////////////////////////////

	List<Integer>[] readGraph(int vertexNumber, int edgeNumber)
	throws IOException{
		@SuppressWarnings("unchecked")
		List<Integer>[] graph = new List[vertexNumber];

		for (int index = 0; index < vertexNumber; ++index){
			graph[index] = new ArrayList<Integer>();
		}

		while (edgeNumber-- > 0){
			int from = readInt() - 1;
			int to = readInt() - 1;

			graph[from].add(to);
			graph[to].add(from);
		}

		return graph;
	}

	/////////////////////////////////////////////////////////////////////

	static class IntIndexPair {

		static Comparator<IntIndexPair> increaseComparator = new Comparator<D.IntIndexPair>() {

			@Override
			public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) {
				int value1 = indexPair1.value;
				int value2 = indexPair2.value;

				if (value1 != value2) return value1 - value2;

				int index1 = indexPair1.index;
				int index2 = indexPair2.index;

				return index1 - index2;
			}
		};

		static Comparator<IntIndexPair> decreaseComparator = new Comparator<D.IntIndexPair>() {

			@Override
			public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) {
				int value1 = indexPair1.value;
				int value2 = indexPair2.value;

				if (value1 != value2) return -(value1 - value2);

				int index1 = indexPair1.index;
				int index2 = indexPair2.index;

				return index1 - index2;
			}
		};

		int value, index;

		public IntIndexPair(int value, int index) {
			super();
			this.value = value;
			this.index = index;
		}

		public int getRealIndex() {
			return index + 1;
		}
	}

	IntIndexPair[] readIntIndexArray(int size) throws IOException {
		IntIndexPair[] array = new IntIndexPair[size];

		for (int index = 0; index < size; ++index) {
			array[index] = new IntIndexPair(readInt(), index);
		}

		return array;
	}

	/////////////////////////////////////////////////////////////////////

	static class OutputWriter extends PrintWriter{

		final int DEFAULT_PRECISION = 12;

		int precision;
		String format, formatWithSpace;

		{
			precision = DEFAULT_PRECISION;

			format = createFormat(precision);
			formatWithSpace = format + " ";
		}

		public OutputWriter(OutputStream out) {
			super(out);
		}

		public OutputWriter(String fileName) throws FileNotFoundException {
			super(fileName);
		}

		public int getPrecision() {
			return precision;
		}

		public void setPrecision(int precision) {
			precision = max(0, precision);
			this.precision = precision;

			format = createFormat(precision);
			formatWithSpace = format + " ";
		}

		private String createFormat(int precision){
			return "%." + precision + "f";
		}

		@Override
		public void print(double d){
			printf(format, d);
		}

		public void printWithSpace(double d){
			printf(formatWithSpace, d);
		}

		public void printAll(double...d){
			for (int i = 0; i < d.length - 1; ++i){
				printWithSpace(d[i]);
			}

			print(d[d.length - 1]);
		}

		@Override
		public void println(double d){
			printlnAll(d);
		}

		public void printlnAll(double... d){
			printAll(d);
			println();
		}
	}

	/////////////////////////////////////////////////////////////////////

	int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
	int[][] steps8 = {
			{-1, 0}, {1, 0}, {0, -1}, {0, 1},
			{-1, -1}, {1, 1}, {1, -1}, {-1, 1}
	};

	boolean check(int index, int lim){
		return (0 <= index && index < lim);
	}

	/////////////////////////////////////////////////////////////////////

	boolean checkBit(int mask, int bit){
		return (mask & (1 << bit)) != 0;
	}

	/////////////////////////////////////////////////////////////////////

	void solve() throws IOException {
		char[] number = readString().toCharArray();
		int n = number.length;

		int md = readInt();

		int lim = (1 << n);
		long[][] dp = new long[lim][md];
		dp[0][0] = 1;

		int[] pows = new int[n];
		pows[0] = 1;
		for (int i = 1; i < n; ++i) {
			pows[i] = pows[i-1] * 10 % md;
		}

		int[] used = new int[10];

		for (int mask = 1; mask < lim; ++mask) {
			int pow = pows[n - Integer.bitCount(mask)];

			for (int bit = 0; bit < n; ++bit) {
				int digit = number[bit] - '0';

				if (checkBit(mask, bit)) {
					int fromMask = (mask ^ (1 << bit));

					if (digit == 0 && fromMask == 0) {
						// bad idea
					} else {
						used[digit] = mask;

						for (int fromRem = 0; fromRem < md; ++fromRem) {
							int curRem = (fromRem + digit * pow) % md;
							dp[mask][curRem] = (dp[mask][curRem] + dp[fromMask][fromRem]);
						}
					}
				}
			}
		}

		long ans = dp[lim-1][0];
		out.println(ans);
	}
}

import java.io.*;
import java.util.*;

public class Main {

    static StringBuilder st = new StringBuilder();
    static int n, m, a[];
    static int[][][][][][][][][][][][] memo;// idx , taken , mod , zero , one , two , three , four , five , six , seven , eight , nine

    static int mult(int a , int b , int MOD) {return (int)((1l * a * b) % MOD) ; }
    static int add(int a , int b , int MOD) {return (a+b) % MOD;}

    static int dp(int idx, int mod, int[] cnt) {

        if (idx == n && mod == 0)
            return 1;

        if (idx == n)
            return 0;

        if (check(idx, mod, cnt))
            return get(idx, mod, cnt);

        int ans = 0 ;
        for (int i = 0; i < 10; i++) {
            if (cnt[i] > 0) {
                int[] newCnt = cnt.clone();
                newCnt[i]--;
                if (i == 0 && idx == 0) continue;
                ans += dp(idx + 1, add(i, mult(10, mod, m), m), newCnt );
            }
        }

        return set(idx, mod, cnt, ans);

    }

    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner();
        PrintWriter out = new PrintWriter(System.out);

        char[] c = sc.next().toCharArray();
        n = c.length;
        m = sc.nextInt();
        init(n, m, c);
        int [] cnt = new int [10];
        for(int x : a)
            cnt[x]++;

        out.println(dp(0, m, cnt));

        out.flush();
        out.close();

    }

    static class Scanner {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st;

        Scanner() {
        }

        Scanner(String path) throws Exception {
            br = new BufferedReader(new FileReader(path));
        }

        String next() throws Exception {
            while (st == null || !st.hasMoreTokens())
                st = new StringTokenizer(br.readLine());
            return st.nextToken();
        }

        int nextInt() throws Exception {
            return Integer.parseInt(next());
        }

        long nextLong() throws Exception {
            return Long.parseLong(next());
        }

        double nextDouble() throws Exception {
            return Double.parseDouble(next());
        }
    }

    static void shuffle(int[] a) {
        int n = a.length;
        for (int i = 0; i < n; i++) {
            int r = i + (int) (Math.random() * (n - i));
            int tmp = a[i];
            a[i] = a[r];
            a[r] = tmp;
        }
    }

    static void shuffle(char[] a) {
        int n = a.length;
        for (int i = 0; i < n; i++) {
            int r = i + (int) (Math.random() * (n - i));
            char tmp = a[i];
            a[i] = a[r];
            a[r] = tmp;
        }
    }

    static void shuffle(long[] a) {
        int n = a.length;
        for (int i = 0; i < n; i++) {
            int r = i + (int) (Math.random() * (n - i));
            long tmp = a[i];
            a[i] = a[r];
            a[r] = tmp;
        }
    }

    private static boolean oj = System.getProperty("ONLINE_JUDGE") != null;

    private static void tr(Object... o) {
        if (!oj)
            System.out.println(Arrays.deepToString(o));
    }

    static boolean check(int idx, int mod, int[] cnt) {
        return (memo[idx][mod][cnt[0]][cnt[1]][cnt[2]][cnt[3]][cnt[4]][cnt[5]][cnt[6]][cnt[7]][cnt[8]][cnt[9]] != -1);
    }

    static int get(int idx, int mod, int[] cnt) {
        return memo[idx][mod][cnt[0]][cnt[1]][cnt[2]][cnt[3]][cnt[4]][cnt[5]][cnt[6]][cnt[7]][cnt[8]][cnt[9]];
    }

    static int set(int idx, int mod, int[] cnt, int val) {
        return memo[idx][mod][cnt[0]][cnt[1]][cnt[2]][cnt[3]][cnt[4]][cnt[5]][cnt[6]][cnt[7]][cnt[8]][cnt[9]] = val;
    }

    static void init(int n, int m, char[] c) {

        a = new int[n];

        for (int i = 0; i < n; i++)
            a[n - i - 1] = c[i] - '0';
        int [] cnt = new int [10];
        for(int x : a)
            cnt[x]++;
        memo = new int[n][m+1][cnt[0]+1][cnt[1]+1][cnt[2]+1][cnt[3]+1][cnt[4]+1][cnt[5]+1][cnt[6]+1][cnt[7]+1][cnt[8]+1][cnt[9]+1];

            for (int[][][][][][][][][][][] xx : memo)
                 for (int[][][][][][][][][][] xxx : xx)
                    for (int[][][][][][][][][] xxxx : xxx)
                        for (int[][][][][][][][] xxxxx : xxxx)
                            for (int[][][][][][][] xxxxxx : xxxxx)
                                for (int[][][][][][] xxxxxxx : xxxxxx)
                                    for (int[][][][][] xxxxxxxx : xxxxxxx)
                                        for (int[][][][] xxxxxxxxx : xxxxxxxx)
                                            for (int[][][] xxxxxxxxxx : xxxxxxxxx)
                                                for (int[][] xxxxxxxxxxx : xxxxxxxxxx)
                                                    for (int[] xxxxxxxxxxxx : xxxxxxxxxxx)
                                                        Arrays.fill(xxxxxxxxxxxx, -1);
    }

}

import java.io.*;
import java.util.*;
/*
 * Heart beats fast
 * 		Colors and promises
 * 			How to be brave
 * 				How can I love when I am afraid...
 */
public class Main
{
	public static void main(String[]args) throws Exception
	{
		long n=nl();
		int m=ni();
		int te=0;
		int lol[]=new int[64];
		long lolo=n;
		for(int i=0; lolo>0; i++,lolo/=10)
		{
			lol[i]=(int)(lolo%10);
			te++;
		}
		long[][]dp=new long[1<<te][m];
		dp[0][0]=1;
		for(int i=0; i<1<<te; i++)
			for(int j=0; j<te; j++)
				if(((i>>j)&1)==0)
					if(i!=0||lol[j]!=0)
					for(int k=0; k<m; k++)
						dp[i+(1<<j)][(k*10+lol[j])%m]+=dp[i][k];
		int[]co=new int[10];
		for(int i=0; i<te; i++)
			co[lol[i]]++;
		for(int i=0; i<10; i++)
			if(co[i]!=0)
				dp[(1<<te)-1][0]/=co[i];
		pr(dp[(1<<te)-1][0]);
		System.out.println(output);
	}
	///////////////////////////////////////////
	///////////////////////////////////////////
	///template from here
	static final int mod=1000_000_007;
	static final double eps=1e-9;
	static final long inf=100000000000000000L;
	static class pair
	{
		int a,b;
		pair(){}
		pair(int c,int d){a=c;b=d;}
		@Override
		public int hashCode()
		{
			return (a+" "+b).hashCode();
		}
		public boolean equals(Object c)
		{
			return (a==(((pair)c).a)&&b==(((pair)c).b));
		}
	}
	public static void sort(int[][]a)
	{
		Arrays.sort(a, new Comparator<int[]>()
				{
			public int compare(int[]a,int[]b)
			{
				if(a[0]>b[0])
					return 1;
				if(a[0]<b[0])
					return -1;
				return 0;
			}
				});
	}
	static interface combiner
	{
		public int combine(int a, int b);
	}
	static void pr(Object a){output.append(a+"\n");}
	static void pr(){output.append("\n");}
	static void p(Object a){output.append(a);}
	static void pra(int[]a){for(int i:a)output.append(i+" ");output.append("\n");}
	static void pra(long[]a){for(long i:a)output.append(i+" ");output.append("\n");}
	static void pra(String[]a){for(String i:a)output.append(i+" ");output.append("\n");}
	static void pra(double[]a){for(double i:a)output.append(i+" ");output.append("\n");}
	static void sop(Object a){System.out.println(a);}
	static void flush(){System.out.print(output);output=new StringBuilder();}
	static int ni(){return Integer.parseInt(in.next());}
	static long nl(){return Long.parseLong(in.next());}
	static String ns(){return in.next();}
	static double nd(){return Double.parseDouble(in.next());}
	static int[] nia(int n){int a[]=new int[n];for(int i=0; i<n; i++)a[i]=ni();return a;}
	static int[] pnia(int n){int a[]=new int[n+1];for(int i=1; i<=n; i++)a[i]=ni();return a;}
	static long[] nla(int n){long a[]=new long[n];for(int i=0; i<n; i++)a[i]=nl();return a;}
	static String[] nsa(int n){String a[]=new String[n];for(int i=0; i<n; i++)a[i]=ns();return a;}
	static double[] nda(int n){double a[]=new double[n];for(int i=0; i<n; i++)a[i]=nd();return a;}
	static Reader in=new Reader();
	static StringBuilder output=new StringBuilder();
	static Random rn=new Random();
	static void reverse(int[]a){for(int i=0; i<a.length/2; i++){a[i]^=a[a.length-i-1];a[a.length-i-1]^=a[i];a[i]^=a[a.length-i-1];}}
	static int log2n(long a)
	{
		int te=0;
		while(a>0)
		{
			a>>=1;
			++te;
		}
		return te;
	}
	static class vectorl implements Iterable<Long>
	{
		long a[];
		int size;
		vectorl(){a=new long[10];size=0;}
		vectorl(int n){a=new long[n];size=0;}
		public void add(long b){if(++size==a.length)a=Arrays.copyOf(a, 2*size);a[size-1]=b;}
		public void sort(){Arrays.sort(a, 0, size);}
		public void sort(int l, int r){Arrays.sort(a, l, r);}
		@Override
		public Iterator<Long> iterator() {
			Iterator<Long> hola=new Iterator<Long>()
					{
				int cur=0;
						@Override
						public boolean hasNext() {
							return cur<size;
						}
						@Override
						public Long next() {
							return a[cur++];
						}
					};
			return hola;
		}
	}
	static class vector implements Iterable<Integer>
	{
		int a[],size;
		vector(){a=new int[10];size=0;}
		vector(int n){a=new int[n];size=0;}
		public void add(int b){if(++size==a.length)a=Arrays.copyOf(a, 2*size);a[size-1]=b;}
		public void sort(){Arrays.sort(a, 0, size);}
		public void sort(int l, int r){Arrays.sort(a, l, r);}
		@Override
		public Iterator<Integer> iterator() {
			Iterator<Integer> hola=new Iterator<Integer>()
					{
				int cur=0;
						@Override
						public boolean hasNext() {
							return cur<size;
						}
						@Override
						public Integer next() {
							return a[cur++];
						}
					};
			return hola;
		}
	}
	static void exit(){System.out.print(output);System.exit(0);}
	static int min(int... a){int min=a[0];for(int i:a)min=Math.min(min, i);return min;}
	static int max(int... a){int max=a[0];for(int i:a)max=Math.max(max, i);return max;}
	static int gcd(int... a){int gcd=a[0];for(int i:a)gcd=gcd(gcd, i);return gcd;}
	static long min(long... a){long min=a[0];for(long i:a)min=Math.min(min, i);return min;}
	static long max(long... a){long max=a[0];for(long i:a)max=Math.max(max, i);return max;}
	static long gcd(long... a){long gcd=a[0];for(long i:a)gcd=gcd(gcd, i);return gcd;}
	static String pr(String a, long b){String c="";while(b>0){if(b%2==1)c=c.concat(a);a=a.concat(a);b>>=1;}return c;}
	static long powm(long a, long b, long m){long an=1;long c=a;while(b>0){if(b%2==1)an=(an*c)%m;c=(c*c)%m;b>>=1;}return an;}
	static int gcd(int a, int b){if(b==0)return a;return gcd(b, a%b);}
	static long gcd(long a, long b){if(b==0)return a;return gcd(b, a%b);}
	static class Reader{
        public BufferedReader reader;
        public StringTokenizer tokenizer;
        public Reader() {
            reader = new BufferedReader(new InputStreamReader(System.in));
            tokenizer = null;
        }
        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;

/**
 * @author Don Li
 */
public class RomanNumbers {

    int n;
    int[] cnt;

    void solve() {
        char[] a = in.nextToken().toCharArray();
        int m = in.nextInt();

        n = a.length;
        cnt = new int[10];
        for (int i = 0; i < n; i++) {
            cnt[a[i] - '0']++;
        }

        int tot = 1;
        for (int i = 0; i < 10; i++) tot *= cnt[i] + 1;

        int[][] dp = new int[m][tot];
        dp[0][tot - 1] = 1;
        for (int s = tot - 1; s > 0; s--) {
            int[] rem = decode(s);
            for (int x = 0; x < m; x++) {
                if (dp[x][s] > 0) {
                    for (int d = 0; d < 10; d++) {
                        if (s == tot - 1 && d == 0 || rem[d] == 0) continue;
                        rem[d]--;
                        int ns = encode(rem);
                        dp[(x * 10 + d) % m][ns] += dp[x][s];
                        rem[d]++;
                    }
                }
            }
        }
        out.println(dp[0][0]);
    }

    int encode(int[] a) {
        int ret = 0;
        for (int i = 0; i < 10; i++) {
            ret = ret * (cnt[i] + 1) + a[i];
        }
        return ret;
    }

    int[] decode(int x) {
        int[] ret = new int[10];
        for (int i = 9; i >= 0; i--) {
            ret[i] = x % (cnt[i] + 1);
            x /= cnt[i] + 1;
        }
        return ret;
    }

    public static void main(String[] args) {
        in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
        out = new PrintWriter(System.out);
        new RomanNumbers().solve();
        out.close();
    }

    static FastScanner in;
    static PrintWriter out;

    static class FastScanner {
        BufferedReader in;
        StringTokenizer st;

        public FastScanner(BufferedReader in) {
            this.in = in;
        }

        public String nextToken() {
            while (st == null || !st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(in.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(nextToken());
        }

        public long nextLong() {
            return Long.parseLong(nextToken());
        }

        public double nextDouble() {
            return Double.parseDouble(nextToken());
        }
    }
}

import java.util.HashMap;
import java.util.Scanner;

public class cf401d {
	public static long factorial(int a) {
		int ret = 1;
		for (int i = 2; i <= a; i++)
			ret *= i;
		return ret;
	}

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);

		long n = in.nextLong();
		int m = in.nextInt();

		String[] Sdigs = ("" + n).split("");
		int[] digs = new int[Sdigs.length];
		for (int i = 0; i < digs.length; i++)
			digs[i] = Integer.parseInt(Sdigs[i]);
		long[][] dp = new long[1 << digs.length][m];

		dp[0][0] = 1;

		for (int i = 0; i < dp.length; i++) {
			for (int dig = 0; dig < digs.length; dig++) {
				if (((i >> dig) & 1) == 1)
					continue;
				if (i == 0 && digs[dig] == 0)
					continue;
				int index = i | (1 << dig);
				for (int j = 0; j < m; j++) {
					int newmod = (10 * j + digs[dig]) % m;
					dp[index][newmod] += dp[i][j];
				}
			}
		}

		long ans = dp[(1 << digs.length) - 1][0];
		HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
		for (int i : digs) {
			if (hm.containsKey(i))
				hm.put(i, hm.get(i) + 1);
			else
				hm.put(i, 1);
		}

		for (int i : hm.keySet())
			ans /= factorial(hm.get(i));

		System.out.println(ans);

		in.close();
	}

	public static void debug(Object o) {
		System.out.println("\tDEBUG: " + o.toString().replaceAll("\n", "\n\tDEBUG: "));
	}
}

import java.io.*;
import java.util.*;

public class Main {

    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        String n1 = in.next();
        String n2 = in.next();
        int m = Integer.parseInt(n2);
        int[] count = new int[10];
        Arrays.fill(count, 0);
        for (int i = 0; i < n1.length(); i++) {
            count[n1.charAt(i) - '0']++;
        }
        int[] f = new int[19];
        f[0] = 1;
        for (int i = 1; i < 19; i++) {
            f[i] = f[i - 1] * i;
        }
        int sh = 1 << n1.length();
        int[][] dp = new int[sh][m];
        for (int s = 0; s < sh; s++) {
            Arrays.fill(dp[s], 0);
        }
        dp[0][0] = 1;
        for (int i = 0; i < sh; i++) {
            for (int j = 0; j < n1.length(); j++) {
                int now = n1.charAt(j) - '0';
                if ((now == 0 && i == 0) || (i & (1 << j)) != 0) {
                    continue;
                }
                for (int k = 0; k < m; k++) {
                    if (dp[i][k] > 0) {
                        int i1 = i | (1 << j);
                        int i2 = (10 * k + now) % m;
                        dp[i1][i2] += dp[i][k];
                    }
                }
            }
        }
        int x = dp[sh - 1][0];
        for (int i = 0; i <= 9; i++) {
            x /= f[count[i]];
        }
        out.println(x);
        out.close();
    }

    static class InputReader {

        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }

}

/*
Keep solving problems.
*/
import java.util.*;
import java.io.*;

public class CF401D {

    BufferedReader br;
    PrintWriter out;
    StringTokenizer st;
    boolean eof;
    final long MOD = 1000L * 1000L * 1000L + 7;
    long[][] dp;
    char[] arr;
    int n;
    int m;
    void solve() throws IOException {
        arr = Long.toString(nextLong()).toCharArray();
        m = nextInt();
        n = arr.length;

        dp = new long[1 << n][m];
        dp[0][0] = 1;

        for(int mask = 0; mask < (1 << n); mask++) {
            for(int rem = 0; rem < m; rem++) {
                if(dp[mask][rem] == 0) {
                    continue;
                }

                for(int i = 0; i < n; i++) {
                    if((mask & (1 << i)) == 0) {
                        if(!(mask == 0 && arr[i] == '0')) {
                            dp[mask + (1 << i)][(rem * 10 + (arr[i] - '0')) % m] += dp[mask][rem];
                        }
                    }
                }
            }
        }

        int[] hist = new int[10];
        for(int i = 0; i < n; i++) {
            hist[arr[i] - '0']++;
        }
        int[] fact = new int[20];
        fact[0] = 1;
        for(int i = 1; i < 20; i++) {
            fact[i] = fact[i - 1] * i;
        }
        long res = dp[(1 << n) - 1][0];
        for(int i = 0; i < hist.length; i++) {
            res /= fact[hist[i]];
        }
        out(res);
    }

    void shuffle(int[] a) {
        int n = a.length;
        for(int i = 0; i < n; i++) {
            int r = i + (int) (Math.random() * (n - i));
            int tmp = a[i];
            a[i] = a[r];
            a[r] = tmp;
        }
    }
    private void outln(Object o) {
        out.println(o);
    }
    private void out(Object o) {
        out.print(o);
    }
    public CF401D() throws IOException {
        br = new BufferedReader(new InputStreamReader(System.in));
        out = new PrintWriter(System.out);
        solve();
        out.close();
    }
    public static void main(String[] args) throws IOException {
        new CF401D();
    }

    public long[] nextLongArr(int n) throws IOException{
        long[] res = new long[n];
        for(int i = 0; i < n; i++)
            res[i] = nextLong();
        return res;
    }
    public int[] nextIntArr(int n) throws IOException {
        int[] res = new int[n];
        for(int i = 0; i < n; i++)
            res[i] = nextInt();
        return res;
    }
    public String nextToken() {
        while (st == null || !st.hasMoreTokens()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (Exception e) {
                eof = true;
                return null;
            }
        }
        return st.nextToken();
    }
    public String nextString() {
        try {
            return br.readLine();
        } catch (IOException e) {
            eof = true;
            return null;
        }
    }
    public int nextInt() throws IOException {
        return Integer.parseInt(nextToken());
    }
    public long nextLong() throws IOException {
        return Long.parseLong(nextToken());
    }
    public double nextDouble() throws IOException {
        return Double.parseDouble(nextToken());
    }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;

	public class Abood2C {
		static int N;
		static int memo[][][][][][][][][][][][];
		static int MOD;
		static int solve(int i, int[] r, int m) {
			if(i == N && m == 0)
				return 1;
			if(i == N)
				return 0;
			if(memo[i][r[0]][r[1]][r[2]][r[3]][r[4]][r[5]][r[6]][r[7]][r[8]][r[9]][m] != -1)
				return memo[i][r[0]][r[1]][r[2]][r[3]][r[4]][r[5]][r[6]][r[7]][r[8]][r[9]][m];

			int ans = 0;
			int[] v = r.clone();
			int p = 1;
			for (int j = 0; j < i; j++) {
				p *= 10;
				p %= MOD;
			}
			for (int j = 0; j < r.length; j++) {
				if(r[j] == 0 || j == 0 && i == N - 1)
					continue;
				v[j]--;
				ans += solve(i + 1, v, (m + p * j) % MOD);
				v[j]++;
			}
			return memo[i][r[0]][r[1]][r[2]][r[3]][r[4]][r[5]][r[6]][r[7]][r[8]][r[9]][m] = ans;
		}

		public static void main(String[] args) throws Exception{
			Scanner sc = new Scanner(System.in);
			PrintWriter out = new PrintWriter(System.out);

			String s = sc.next();
			N = s.length();
			MOD = sc.nextInt();

			int[] r = new int[10];
			for (int i = 0; i < s.length(); i++)
				r[s.charAt(i) - '0']++;
			memo = new int [N][r[0] + 1][r[1] + 1][r[2] + 1][r[3] + 1][r[4] + 1][r[5] + 1][r[6] + 1][r[7] + 1][r[8] + 1][r[9] + 1][MOD];
			for (int i = 0; i < N; i++)
				for (int j = 0; j <= r[0]; j++)
					for (int j2 = 0; j2 <= r[1]; j2++)
						for (int k = 0; k <= r[2]; k++)
							for (int k2 = 0; k2 <= r[3]; k2++)
								for (int l = 0; l <= r[4]; l++)
									for (int l2 = 0; l2 <= r[5]; l2++)
										for (int m = 0; m <= r[6]; m++)
											for (int m2 = 0; m2 <= r[7]; m2++)
												for (int o = 0; o <= r[8]; o++)
													for (int o2 = 0; o2 <= r[9]; o2++)
															Arrays.fill(memo[i][j][j2][k][k2][l][l2][m][m2][o][o2], -1);

			out.println(solve(0, r, 0));

			out.flush();
			out.close();
		}

		static class Scanner
		{
			StringTokenizer st;
			BufferedReader br;

			public Scanner(InputStream System){	br = new BufferedReader(new InputStreamReader(System));}
			public String next() throws IOException
			{
				while (st == null || !st.hasMoreTokens())
					st = new StringTokenizer(br.readLine());
				return st.nextToken();
			}
			public String nextLine()throws IOException{return br.readLine();}
			public int nextInt() throws IOException {return Integer.parseInt(next());}
			public double nextDouble() throws IOException {return Double.parseDouble(next());}
			public char nextChar()throws IOException{return next().charAt(0);}
			public Long nextLong()throws IOException{return Long.parseLong(next());}
			public boolean ready() throws IOException{return br.ready();}
			public void waitForInput(){for(long i = 0; i < 3e9; i++);}
		}
	}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;

	public class Abood2C {
		static int N;
		static long memo[][][][][][][][][][][][];
		static int MOD;
		static long solve(int i, int[] r, int m) {
			if(i == N && m == 0)
				return 1;
			if(i == N)
				return 0;
			if(memo[i][r[0]][r[1]][r[2]][r[3]][r[4]][r[5]][r[6]][r[7]][r[8]][r[9]][m] != -1)
				return memo[i][r[0]][r[1]][r[2]][r[3]][r[4]][r[5]][r[6]][r[7]][r[8]][r[9]][m];

			int ans = 0;
			int[] v = r.clone();
			int p = 1;
			for (int j = 0; j < i; j++) {
				p *= 10;
				p %= MOD;
			}
			for (int j = 0; j < r.length; j++) {
				if(r[j] == 0 || j == 0 && i == N - 1)
					continue;
				v[j]--;
				ans += solve(i + 1, v, (m + p * j) % MOD);
				v[j]++;
			}
			return memo[i][r[0]][r[1]][r[2]][r[3]][r[4]][r[5]][r[6]][r[7]][r[8]][r[9]][m] = ans;
		}

		public static void main(String[] args) throws Exception{
			Scanner sc = new Scanner(System.in);
			PrintWriter out = new PrintWriter(System.out);

			String s = sc.next();
			N = s.length();
			MOD = sc.nextInt();

			int[] r = new int[10];
			for (int i = 0; i < s.length(); i++)
				r[s.charAt(i) - '0']++;
			memo = new long [N][r[0] + 1][r[1] + 1][r[2] + 1][r[3] + 1][r[4] + 1][r[5] + 1][r[6] + 1][r[7] + 1][r[8] + 1][r[9] + 1][MOD];
			for (int i = 0; i < N; i++)
				for (int j = 0; j <= r[0]; j++)
					for (int j2 = 0; j2 <= r[1]; j2++)
						for (int k = 0; k <= r[2]; k++)
							for (int k2 = 0; k2 <= r[3]; k2++)
								for (int l = 0; l <= r[4]; l++)
									for (int l2 = 0; l2 <= r[5]; l2++)
										for (int m = 0; m <= r[6]; m++)
											for (int m2 = 0; m2 <= r[7]; m2++)
												for (int o = 0; o <= r[8]; o++)
													for (int o2 = 0; o2 <= r[9]; o2++)
															Arrays.fill(memo[i][j][j2][k][k2][l][l2][m][m2][o][o2], -1);

			out.println(solve(0, r, 0));

			out.flush();
			out.close();
		}

		static class Scanner
		{
			StringTokenizer st;
			BufferedReader br;

			public Scanner(InputStream System){	br = new BufferedReader(new InputStreamReader(System));}
			public String next() throws IOException
			{
				while (st == null || !st.hasMoreTokens())
					st = new StringTokenizer(br.readLine());
				return st.nextToken();
			}
			public String nextLine()throws IOException{return br.readLine();}
			public int nextInt() throws IOException {return Integer.parseInt(next());}
			public double nextDouble() throws IOException {return Double.parseDouble(next());}
			public char nextChar()throws IOException{return next().charAt(0);}
			public Long nextLong()throws IOException{return Long.parseLong(next());}
			public boolean ready() throws IOException{return br.ready();}
			public void waitForInput(){for(long i = 0; i < 3e9; i++);}
		}
	}

import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;

/**
 * Built using CHelper plug-in Actual solution is at the top
 */
public class Main {
	public static void main(String[] args) {
		TaskD t = new TaskD();
		t.solve();
	}
}

class TaskD {
	long ways[][];
	char no[];
	int m;
	int len;

	public void solve() {
		Scanner scan = new Scanner(System.in);
		no = (scan.nextLong() + "").toCharArray();
		len = no.length;
		m = scan.nextInt();
		ways = new long[1 << len][m];
		for (long[] a : ways)
			Arrays.fill(a, -1);
		System.out.println(waysToGetRemWithNums((1 << len) - 1, 0, 0));
//		for (int i = ways.length - 1; i >= 0; i--) {
//			System.out.println(Integer.toBinaryString(i) + ": " + Arrays.toString(ways[i]));
//		}
	}

	long waysToGetRemWithNums(int mask, int rem, int depth) {
		depth++;
		String tabs = "";
		for (int i = 0; i < depth; i++, tabs = tabs + "\t")	;
		// rem = rem*10%m;
		if (mask == 0) {
			if (rem == 0) {
				ways[mask][rem] = 1;
				return 1;
			}
			ways[mask][rem] = 0;
			return 0;
		}
		HashSet<Character> hs = new HashSet<Character>();
		if (ways[mask][rem] != -1)
			return ways[mask][rem];
		long ans = 0;
		// System.out.println(tabs + "how many ways with mask " + Integer.toBinaryString(mask) + " to make remainder " + rem +"?");
		for (int i = 0; i < len; i++) {
			if (((mask >> i) & 1) == 0)
				continue;
			if (depth == len - 1 && no[i] == '0')
				continue;
			if (hs.contains(no[i]))
				continue;
			hs.add(no[i]);
			int remainderNeeded = -1;
			// find the remainder that solves (r1*10 + k) %M == r0
			int k = no[i] - '0';
			for (int j = 0; j < m; j++) {
				if ((j * 10 + k) % m == rem) {
					remainderNeeded = j;
					// System.out.println(tabs + "need to make mask " + Integer.toBinaryString((mask & ~(1<<i))));
					// System.out.println(tabs + " with remainder " + remainderNeeded);

					ans += waysToGetRemWithNums(mask & ~(1 << i), remainderNeeded, depth);
					// ans += go(mask | (1 << i), ((rem * 10) + no[i] - '0') % m);
				}
			}
		}
		// System.out.println(tabs + "ans: " + ans);
		return ways[mask][rem] = ans;
	}

}