#include <iostream>
#include <cstring>
using namespace std;
int a[1550];
#define LL long long int
// returns the square sum of digits
int sqSum(LL num){
int ans=0;
while(num){
ans=ans+(num%10)*(num%10);
num/=10;
}
return ans;
}
void pre(){
fill(a,a+1550,0);
int temp,last;
a[0]=0;a[1]=1;
for(int i=2;i<1550;i++){
if(a[i]==0){// condition if the current value is not processed
a[i]=-1;// let us assume -1 ->infinite loop and +1 for other case
//here i'm assuming that series is infinote
temp=sqSum(i);
while(a[temp]==0){
a[temp]=-1;
temp=sqSum(temp);
}
// if series is not infinite then again calculate
if(a[temp]==1){
a[i]=1;
temp=sqSum(i);
while(a[temp]!=1){
a[temp]=1;
temp=sqSum(temp);
}
}
}
}
}
int main() {
pre();
LL n,m;
while(1){
scanf("%lld %lld",&n,&m);
if(!n&&!m) break;
LL count=0;
for(LL i=n;i<=m;i++){
if(a[sqSum(i)]==-1) count++;
}
printf("%lld\n",count);
}
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8Y3N0cmluZz4KdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCmludCBhWzE1NTBdOwoKI2RlZmluZSBMTCBsb25nIGxvbmcgaW50Ci8vIHJldHVybnMgdGhlIHNxdWFyZSBzdW0gb2YgZGlnaXRzCmludCBzcVN1bShMTCBudW0pewoJaW50IGFucz0wOwoJCgl3aGlsZShudW0pewoJCWFucz1hbnMrKG51bSUxMCkqKG51bSUxMCk7CgkJbnVtLz0xMDsKCX0KICAgIAogICAgcmV0dXJuIGFuczsKCQp9Cgp2b2lkIHByZSgpewoJZmlsbChhLGErMTU1MCwwKTsKCQoJaW50IHRlbXAsbGFzdDsKCQoJYVswXT0wO2FbMV09MTsKCQoJZm9yKGludCBpPTI7aTwxNTUwO2krKyl7CgkJaWYoYVtpXT09MCl7Ly8gY29uZGl0aW9uIGlmIHRoZSBjdXJyZW50IHZhbHVlIGlzIG5vdCBwcm9jZXNzZWQKCQkJYVtpXT0tMTsvLyBsZXQgdXMgYX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