import Control.Applicative import Control.Monad import Data.Int import Data.List (sort) getInts :: IO [Int64] getInts = map (fromIntegral . read) . words <$> getLine factor :: Int64 -> [(Int64, Int64)] factor x = helper x 2 where helper x y | y * y > x = if x /= 1 then [(x, 1)] else [] | x `mod` y == 0 = let (n, x') = f x y 0 in (y, n) : helper x' (y+1) | otherwise = helper x (y+1) f x y a | x `mod` y == 0 = f (x`div`y) y (a+1) | otherwise = (a, x) main = do q <- readLn query <- replicateM q getInts let m = 100000009 count n x t | n `mod` x == 0 = count (n`div`x) x (t+1) | otherwise = t f x 0 = [x] f x n = x : (f x' (n-1)) where x' = 1+(x*x`mod`m + x*12345`mod`m) `mod` m g [seed,n,k,b] = minimum $ map h fs where xs = f seed n fs = factor b h (p,q) = (`div`q) . sum . take (fromIntegral k) . sort $ map (\x -> count x p 0) xs in mapM (print . g) query