// C# program to count Numbers in Range
// with difference between Sum of digits
// at even and odd positions as Prime
using System;
using System.Collections.Generic;
class GfG {
static int countRecur(int i, int diff, int tight, string num,
HashSet<int> primes, int[,,] memo) {
if (i == num.Length) {
if (primes.Contains(diff)) {
return 1;
}
return 0;
}
if (memo[i, diff + 90, tight] != -1) {
return memo[i, diff + 90, tight];
}
int ans = 0;
int digit = num[i] - '0';
// Check if tight constraint is still
// present.
int limit = tight == 1 ? digit : 9;
for (int j = 0; j <= limit; j++) {
// Set new diff on basis of odd
// or even index.
int newDiff = (num.Length - i) % 2 == 1 ? diff - j : diff + j;
ans += countRecur(i + 1, newDiff,
tight == 1 && (j == digit)?1:0, num, primes, memo);
}
memo[i, diff + 90, tight] = ans;
return ans;
}
static int count(int l, int r) {
// Set to store the first
// 100 prime numbers.
HashSet<int> primes = new HashSet<int>() {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97
};
// Memoization table (19 digits, 181
// diff range, 2 tight conditions)
int[,,] memo = new int[19, 181, 2];
for (int i = 0; i < 19; i++) {
for (int j = 0; j < 181; j++) {
for (int k = 0; k < 2; k++) {
memo[i, j, k] = -1;
}
}
}
// Get count of [0, r]
string r1 = r.ToString();
int rCnt = countRecur(0, 0, 1, r1, primes, memo);
// Reset dp
for (int i = 0; i < 19; i++) {
for (int j = 0; j < 181; j++) {
for (int k = 0; k < 2; k++) {
memo[i, j, k] = -1;
}
}
}
// Get count of [0, l-1]
string l1 = (l - 1).ToString();
int lCnt = countRecur(0, 0, 1, l1, primes, memo);
return rCnt - lCnt;
}
static void Main(string[] args) {
int l = 1, r = 50;
Console.WriteLine(count(l, r));
}
}