#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
LL dp[22][81 * 20][9 * 20][2];
LL F(LL x)
{
char str[20];
sprintf(str,"%lld",x);
int N = strlen(str) , i , j , k , l , m;
dp[N][0][0][1] = 1;
for(i=N-1;i>=0;--i)
for(j=0;j<=81*(N-i);++j)
for(k=0;k<=(9*(N-i));++k)
for(l=0;l<2;++l)
{
dp[i][j][k][l] = 0;
for(m=0;m<=(l?9:str[i]-'0');++m)
if(j>=m*m && k>=m)
dp[i][j][k][l]+=dp[i+1][j-m*m][k-m][l || m<str[i]-'0'];
}
LL ret = 0;
for(j=0;j<=81*(N);++j)
for(k=0;k<=(9*(N));++k)
if(__gcd(j,k)==1)
ret+=dp[0][j][k][0];
for(i=N-1;i>=0;--i)
for(j=0;j<=81*(N-i);++j)
for(k=0;k<=(9*(N-i));++k)
for(l=0;l<2;++l)
dp[i][j][k][l] = 0 ;
dp[N][0][0][1] = 0;
return ret;
}
int main()
{
int T;
scanf("%d",&T);
for(;T;--T)
{
LL A , B ;
scanf("%lld%lld",&A,&B);
printf("%lld\n",F(B+1)-F(A));
}
return 0;
}
I2luY2x1ZGU8Yml0cy9zdGRjKysuaD4KdXNpbmcgbmFtZXNwYWNlIHN0ZDsKdHlwZWRlZiBsb25nIGxvbmcgTEw7CkxMIGRwWzIyXVs4MSAqIDIwXVs5ICogMjBdWzJdOwpMTCBGKExMIHgpCnsKCiAgICBjaGFyIHN0clsyMF07CiAgICBzcHJpbnRmKHN0ciwiJWxsZCIseCk7CiAgICBpbnQgTiA9IHN0cmxlbihzdHIpICwgaSAsIGogLCBrICwgbCAsIG07CiAgICBkcFtOXVswXVswXVsxXSA9IDE7CgogICAgZm9yKGk9Ti0xO2k+PTA7LS1pKQogICAgICAgIGZvcihqPTA7ajw9ODEqKE4taSk7KytqKQogICAgICAgICAgICBmb3Ioaz0wO2s8PSg5KihOLWkpKTsrK2spCiAgICAgICAgICAgICAgICBmb3IobD0wO2w8MjsrK2wpCiAgICAgICAgICAgICAgICAgICAgewogICAgICAgICAgICAgICAgICAgICAgICBkcFtpXVtqXVtrXVtsXSA9IDA7CiAgICAgICAgICAgICAgICAgICAgICAgIGZvcihtPTA7bTw9KGw/OTpzdHJbaV0tJzAnKTsrK20pCiAgICAgICAgICAgICAgICAgICAgICAgICAgICBpZihqPj1tKm0gJiYgaz49bSkKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBkcFtpXVtqXVtrXVtsXSs9ZHBbaSsxXVtqLW0qbV1bay1tXVtsIHx8IG08c3RyW2ldLScwJ107CiAgICAgICAgICAgICAgICAgICAgfQogICAgTEwgcmV0ID0gMDsKCiAgICBmb3Ioaj0wO2o8PTgxKihOKTsrK2opCiAgICAgICAgZm9yKGs9MDtrPD0oOSooTikpOysraykKICAgICAgICAgICAgaWYoX19nY2QoaixrKT09MSkKICAgICAgICAgICAgICAgIHJldCs9ZHBbMF1bal1ba11bMF07CgogICAgZm9yKGk9Ti0xO2k+PTA7LS1pKQogICAgICAgIGZvcihqPTA7ajw9ODEqKE4taSk7KytqKQogICAgICAgICAgICBmb3Ioaz0wO2s8PSg5KihOLWkpKTsrK2spCiAgICAgICAgICAgICAgICBmb3IobD0wO2w8MjsrK2wpCiAgICAgICAgICAgICAgICAgICAgICAgIGRwW2ldW2pdW2tdW2xdID0gMCA7CiAgICBkcFtOXVswXVswXVsxXSA9IDA7CiAgICByZXR1cm4gcmV0Owp9CgoKaW50IG1haW4oKQp7CgogICAgaW50IFQ7CiAgICBzY2FuZigiJWQiLCZUKTsKICAgIGZvcig7VDstLVQpCiAgICB7CiAgICAgICAgTEwgQSAsIEIgOwogICAgICAgIHNjYW5mKCIlbGxkJWxsZCIsJkEsJkIpOwogICAgICAgIHByaW50ZigiJWxsZFxuIixGKEIrMSktRihBKSk7CiAgICB9CiAgICByZXR1cm4gMDsKfQo=