require'prime' def f(a,t)t%a>0?0:1+f(a,t/a)end gets.to_i.times{s,n,k,b=gets.split.map &:to_i;x=[s];n.times{x<<1+(x[-1]**2+x[-1]*12345)%100000009};p b.prime_division.map{|a|x.map{|t|f(a[0],t)}.sort[0...k].inject(:+)/a[1]}.min}