GONE - G-One Numbers
The War of Evil vs Good continues and Ra-One and G-One continue to be on respective sides.
After saving all the cities with Ra-One Numbers G-One realised that some cities whose population is a "G-One Number" can be easy target for Ra-One.
A G-One number is a number sum of whose digits is a prime number
For eg. 12 .. sum = 1+2 =3 ... 3 is a prime number.
G-One wants to find out all the populations which can be g-One numbers....
Can You help Him.?
You will be given the range of population and you have to tell him how many in this range are G-One Numbers.
Input
first line has number 'c' indicating the number of ranges.
'c' lines follow and contain two numbers ..... 'f' and 't' inclusive.
Output
Print a single line per case giving the number of populations which are G-One numbers.
Example
Input: 3
10 19
1 9
20 29
Output:
4
4
5
Note: c will be less than 100
t and f will be less than 10^8 inclusive
/*
链接:http://www.spoj.com/problems/GONE/en/
题意:求区间各位和为质数的数的个数
思路:数位dp
*/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<set>
#include<map>
#define L(x) (x<<1)
#define R(x) (x<<1|1)
#define MID(x,y) ((x+y)>>1)
#define bug printf("hihi\n")
#define eps 1e-8
using namespace std;
#define INF 0x3f3f3f3f
#define N 105
int dp[15][N];
int bit[25];
int pri[N];
void inint()
{
int i,j;
pri[0]=pri[1]=1;
for(i=2;i<N;i++)
if(!pri[i])
for(j=i*2;j<N;j+=i)
pri[j]=1;
}
int dfs(int pos,int all,bool bound)
{
if(pos==0) return pri[all] ? 0:1;
if(!bound&&dp[pos][all]>=0) return dp[pos][all];
int up=bound?bit[pos]:9;
int ans=0;
for(int i=0;i<=up;i++)
ans+=dfs(pos-1,all+i,bound&&i==up);
if(!bound) dp[pos][all]=ans;
return ans;
}
int solve(int x)
{
int i,j;
int len=0;
while(x)
{
bit[++len]=x%10;
x/=10;
}
return dfs(len,0,true);
}
int main()
{
int i,j,le,ri,t;
inint();
memset(dp,-1,sizeof(dp));
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&le,&ri);
printf("%d\n",solve(ri)-solve(le-1));
}
return 0;
}