#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;
}