#include <bits/stdc++.h>
using namespace std;
#define int long long
main ()
{
cin.tie(0); cout.sync_with_stdio(false);
int N;
stack<int> numbers;
while (cin>>N) {
if (!N) {
queue<int> div, undiv;
int maxN;
while (numbers.size()) {
numbers.top()%7==0 ? div.push(numbers.top()):undiv.push(numbers.top());
numbers.pop();
}
if (div.size()) {
int m = -1;
while (div.size()) {
if (m <= div.front()%70) {
m = div.front()%70;
maxN = div.front();
}
div.pop();
}
cout<<maxN;
}
else {
int m = 80;
while (undiv.size()) {
if (m >= undiv.front()%77) {
m = undiv.front()%77;
maxN = undiv.front();
}
undiv.pop();
}
cout<<maxN;
}
}else numbers.push(N);
}
}