#include <bits/stdc++.h>
using namespace std;
int vis[100005];
int n,m;
int bushu;
bool check(int tt){
if(tt%3==0||tt%7==0)
return true;
return false;
}
int bfs(){
queue<int> q;
q.push(n);
vis[n]=1;
bushu=0;
while(!q.empty()){
int len=q.size();
for(int i=0;i<len;i++){
int tx,x=q.front();
q.pop();
if(x==m){
return true;
}
for(int i=0;i<3;i++){
if(i==0){
for(int j=0;j<10;j++){
tx=x/10*10+j;
if(tx<100||vis[tx]==1||!check(tx))
continue;
vis[tx]=1;
q.push(tx);
}
}
if(i==1){
for(int j=0;j<10;j++){
tx=x/100*100+j*10+x%10;
if(tx<100||vis[tx]==1||!check(tx))
continue;
vis[tx]=1;
q.push(tx);
}
}
if(i==2){
for(int j=0;j<10;j++){
tx=j*100+x%100;
if(tx<100||vis[tx]==1||!check(tx))
continue;
vis[tx]=1;
q.push(tx);
}
}
}
}
bushu++;
}
return false;
}
int main() {
while(cin>>n>>m){
memset(vis,0,sizeof(vis));
if(bfs()){
cout<<bushu<<endl;
}else{
cout<<"-1"<<endl;
}
}
return 0;
}