MAX = 10**18 MAX_POW = MAX.to_s(2).length - 1 POW2 = [] 1.upto(MAX_POW){|i| POW2 << 2 ** i } def solve(p) candidates = POW2.dup POW2.each{|x| candidates << x%p } candidates.sort! candidates.each do |x| return x if 2.pow(x,p) == x%p end '-1' end n = gets.to_i n.times{ puts solve(gets.to_i) }