import java.math.BigInteger;

public class Euler387 {
    private static boolean isPrime(long n) {
        if (n < 2)
            return false;
        long[] smallPrimes = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37 };
        for (long p : smallPrimes) {
            if (n == p)
                return true;
            if (n % p == 0)
                return false;
        }
        BigInteger bn = BigInteger.valueOf(n);
        BigInteger bnMinus1 = bn.subtract(BigInteger.ONE);
        long d = n - 1;
        int s = 0;
        while ((d & 1) == 0) {
            d >>= 1;
            s++;
        }
        long[] bases = { 2, 3, 5, 7, 11, 13, 17 };
        for (long a : bases) {
            if (a >= n)
                continue;
            BigInteger ba = BigInteger.valueOf(a);
            BigInteger x = ba.modPow(BigInteger.valueOf(d), bn);
            if (x.equals(BigInteger.ONE) || x.equals(bnMinus1))
                continue;
            boolean witness = true;
            for (int r = 1; r < s; r++) {
                x = x.multiply(x).mod(bn);
                if (x.equals(bnMinus1)) {
                    witness = false;
                    break;
                }
            }
            if (witness)
                return false;
        }
        return true;
    }

    private static long dfsHarshad(long n, int digitSum, long harshadLimit, long primeLimit) {
        long acc = 0;
        if (n >= 10 && n % digitSum == 0) {
            long q = n / digitSum;
            if (isPrime(q)) {
                int[] ds = { 1, 3, 7, 9 };
                for (int d : ds) {
                    long cand = n * 10 + d;
                    if (cand < primeLimit && isPrime(cand)) {
                        acc += cand;
                    }
                }
            }
        }

        if (n > harshadLimit / 10)
            return acc;

        for (int d = 0; d <= 9; d++) {
            long next = n * 10 + d;
            int nextSum = digitSum + d;
            if (nextSum != 0 && next % nextSum == 0) {
                acc += dfsHarshad(next, nextSum, harshadLimit, primeLimit);
            }
        }
        return acc;
    }

    public static String solve() {
        long limit = 100000000000000L;
        long harshadLimit = (limit - 1) / 10;
        long total = 0;
        for (int d = 1; d <= 9; d++) {
            total += dfsHarshad(d, d, harshadLimit, limit);
        }
        return String.valueOf(total);
    }

    public static void main(String[] args) {
        System.out.println(solve());
    }
}
