n,a,b=(1..3).map{read_line.split.map &.to_i} n,m=n p (0...n*m).find -2{|x|a[x%n]==b[x%m]}+1