#!/usr/bin/ruby
while (a,b,c=gets.split.map(&:to_i))!=[-1,-1,-1]
	if 2.step(16).none?{|base|a.to_s(base).to_i==b} then p -1;next end
	(a+1).step(c){|i|
		bn=1e9
		2.step(16).map{|base|z=i.to_s(base).to_i;next if z==0;bn=z if b<=z && z<bn}
		b=bn
	}
	p b
end