{-# LANGUAGE Safe #-}
{-# LANGUAGE MultiWayIf #-}

import Control.Applicative
import Control.Monad
import Data.List
import qualified Data.ByteString.Char8 as BS
import Data.Maybe
import Text.Printf
import qualified Data.IntMap as IM
import Data.Ratio
import Control.Monad.State
import Data.Array.IO.Safe
import Data.Int

readIntBS = fst . fromJust . BS.readInt

main = do
  [n,k] <- map read . words <$> getLine :: IO [Int]
  let m = 998244353

  --      UL
  -- 1 => BB
  -- 2 => BW
  -- 3 => WB
  -- 4 => WW

  dp <- newArray ((0,0,1),(n,k+2,4)) 0 :: IO (IOUArray (Int,Int,Int) Int64)

  writeArray dp (1,1,1) 1
  writeArray dp (1,2,2) 1
  writeArray dp (1,2,3) 1
  writeArray dp (1,1,4) 1

  forM_ [2..n] $ \i -> do
    forM_ [1..k] $ \j -> do
      --BB
      writeArray dp (i,j,1) =<< (\a b c d -> (a+b+c+d)`mod`m) <$>
        readArray dp (i-1,j,1) <*> readArray dp (i-1,j,2) <*> readArray dp (i-1,j,3) <*> readArray dp (i-1,j-1,4)
      --BW
      when (j>1) $ do
        writeArray dp (i,j,2) =<< (\a b c d -> (a+b+c+d)`mod`m) <$>
          readArray dp (i-1,j-1,1) <*> readArray dp (i-1,j,2) <*> readArray dp (i-1,j-2,3) <*> readArray dp (i-1,j-1,4)
      --WB
      when (j>1) $ do
        writeArray dp (i,j,3) =<< (\a b c d -> (a+b+c+d)`mod`m) <$>
          readArray dp (i-1,j-1,1) <*> readArray dp (i-1,j-2,2) <*> readArray dp (i-1,j,3) <*> readArray dp (i-1,j-1,4)
      --WW
      writeArray dp (i,j,4) =<< (\a b c d -> (a+b+c+d)`mod`m) <$>
        readArray dp (i-1,j-1,1) <*> readArray dp (i-1,j,2) <*> readArray dp (i-1,j,3) <*> readArray dp (i-1,j,4)

  --print =<< (forM [1..n] $ \i -> (forM [1..k] $ \j -> forM [1..4] $ \l -> readArray dp (i,j,l)))

  print =<< (\a b c d -> (a+b+c+d)`mod`m) <$> readArray dp (n,k,1) <*> readArray dp (n,k,2) <*> readArray dp (n,k,3) <*> readArray dp (n,k,1)

{-# LANGUAGE Safe #-}

import Control.Applicative
import Control.Monad
import Data.List
import qualified Data.IntMap as IM
import Data.Array.IO.Safe
import Data.Int

main = do
  [n,k] <- map read . words <$> getLine :: IO [Int]
  let m = 998244353

  --      UL
  -- 1 => BB
  -- 2 => BW
  -- 3 => WB
  -- 4 => WW

  dp <- newArray ((0,0,1),(n,k+2,4)) 0 :: IO (IOUArray (Int,Int,Int) Int64)

  writeArray dp (1,1,1) 1
  writeArray dp (1,2,2) 1
  writeArray dp (1,2,3) 1
  writeArray dp (1,1,4) 1

  forM_ [2..n] $ \i -> do
    forM_ [1..k] $ \j -> do
      --BB
      writeArray dp (i,j,1) =<< (\a b c d -> (a+b+c+d)`mod`m) <$>
        readArray dp (i-1,j,1) <*> readArray dp (i-1,j,2) <*> readArray dp (i-1,j,3) <*> readArray dp (i-1,j-1,4)
      --BW
      when (j>1) $ do
        writeArray dp (i,j,2) =<< (\a b c d -> (a+b+c+d)`mod`m) <$>
          readArray dp (i-1,j-1,1) <*> readArray dp (i-1,j,2) <*> readArray dp (i-1,j-2,3) <*> readArray dp (i-1,j-1,4)
      --WB
      when (j>1) $ do
        writeArray dp (i,j,3) =<< (\a b c d -> (a+b+c+d)`mod`m) <$>
          readArray dp (i-1,j-1,1) <*> readArray dp (i-1,j-2,2) <*> readArray dp (i-1,j,3) <*> readArray dp (i-1,j-1,4)
      --WW
      writeArray dp (i,j,4) =<< (\a b c d -> (a+b+c+d)`mod`m) <$>
        readArray dp (i-1,j-1,1) <*> readArray dp (i-1,j,2) <*> readArray dp (i-1,j,3) <*> readArray dp (i-1,j,4)

  print =<< (\a b c d -> (a+b+c+d)`mod`m) <$> readArray dp (n,k,1) <*> readArray dp (n,k,2) <*> readArray dp (n,k,3) <*> readArray dp (n,k,4)


{-# LANGUAGE ViewPatterns #-}
import qualified Data.ByteString.Lazy.Char8 as P
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
import System.IO
import Control.Monad.Trans.State

--import Data.ByteString.Builder.Extra (flush) -- for interactive problems
import Control.Monad
import Data.List
import Data.Array.Unboxed

solve :: UArray Int Int -> Int -> Int
solve arr d = let
  (0, (+ 1) -> n) = bounds arr
  numOrbits = gcd n d
  orbitSize = n `div` numOrbits
  step incr ix = if  ix + incr >= n  then  ix + incr - n  else  ix + incr
  getOrbit k = map (arr !) $ take orbitSize $ iterate (step d) k
  evalOne orbit = if  foldl' (+) 0 orbit == orbitSize
    then  maxBound
    else  foldl' max 0 [length vs | vs@(1:_) <- group (orbit ++ orbit)]
  allOrbits = map getOrbit [0 .. numOrbits - 1]
  ans = foldl' max 0 $ map evalOne allOrbits
  in  if  ans == maxBound
  then  0-1
  else  ans

mainFun :: SO
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n, d] <- getInts 2
    a <- listArray (0, n-1) <$> getInts n
    pure $ putInts [solve a d]

type SP = State [P.ByteString]
type SO = SP Builder

getNext :: Int -> SP [P.ByteString]
getNext = state . splitAt

getInts :: Int -> SP [Int]
getInts k = do
  vs <- getNext k
  pure [v | Just (v, _) <- map P.readInt vs]

putInts :: [Int] -> Builder
putInts vs = let
  sepPrim = (,) ' ' Prim.>$<
    Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec
  in  case  vs  of
  [] -> char7 '\n'
  x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\n'

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  inp <- P.getContents
  let  outp = evalState mainFun $ P.words inp
  P.putStr $ toLazyByteString outp

{-# LANGUAGE ViewPatterns #-}
import qualified Data.ByteString.Lazy.Char8 as P
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
import System.IO
import Control.Monad.Trans.State

--import Data.ByteString.Builder.Extra (flush) -- for interactive problems
import Control.Monad
import Data.List
import Data.Array.Unboxed

solve :: UArray Int Int -> Int -> Int
solve arr d = let
  (0, (+ 1) -> n) = bounds arr
  numOrbits = gcd n d
  orbitSize = n `div` numOrbits
  step incr ix = if  ix + incr >= n  then  ix + incr - n  else  ix + incr
  getOrbitTwice k = map (arr !) $ take (2 * orbitSize) $ iterate (step d) k
  evalOne orbit -- Do not traverse an in-memory linked list: It's slow.
    = foldl' max 0 [length vs | vs@(1:_) <- group orbit]
  allOrbitsTwice = map getOrbitTwice [0 .. numOrbits - 1]
  ans = foldl' max 0 $ map evalOne allOrbitsTwice
  in  if  ans >= orbitSize
  then  0-1
  else  ans

mainFun :: SO
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n, d] <- getInts 2
    a <- listArray (0, n-1) <$> getInts n
    pure $ putInts [solve a d]

type SP = State [P.ByteString]
type SO = SP Builder

getNext :: Int -> SP [P.ByteString]
getNext = state . splitAt

getInts :: Int -> SP [Int]
getInts k = do
  vs <- getNext k
  pure [v | Just (v, _) <- map P.readInt vs]

putInts :: [Int] -> Builder
putInts vs = let
  sepPrim = (,) ' ' Prim.>$<
    Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec
  in  case  vs  of
  [] -> char7 '\n'
  x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\n'

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  inp <- P.getContents
  let  outp = evalState mainFun $ P.words inp
  P.putStr $ toLazyByteString outp


import Control.Monad
import Data.Bits
import Data.Char

printPair :: Int -> Int -> IO ()
printPair x y = putStrLn . unwords $ map show [x, y]

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $ do
    n <- read <$> getLine
    a <- replicateM n getLine
    let
      ra = reverse $ map reverse a
      pc = (a !! 0) !! 1
      qc = (a !! 1) !! 0
      xc = (ra !! 0) !! 1
      yc = (ra !! 1) !! 0
      [p, q, x, y] = map (\v -> ord v - ord '0') [pc, qc, xc, yc]
      sw = p + q - x - y
      c = 2 - abs sw
    print c
    when (xor (sw >= 0) (p > 0)) (printPair 1 2)
    when (xor (sw >= 0) (q > 0)) (printPair 2 1)
    when (xor (sw >= 0) (x == 0)) (printPair n (n-1))
    when (xor (sw >= 0) (y == 0)) (printPair (n-1) n)

import Control.Arrow ((>>>))
import Data.Maybe (catMaybes)

main :: IO ()
main = interact $ lines >>> drop 1 >>> process >>> unlines

process :: [String] -> [String]
process [] = []
process (nn : xs) = show (length ys) : ys ++ process (drop n xs)
  where
    n = read nn
    ys = solve n (take n xs)

solve :: Int -> [String] -> [String]
solve n xs = map (\(x, y) -> show x ++ " " ++ show y) . catMaybes $ go (at 2 1) (at 1 2) (at n (n - 1)) (at (n - 1) n)
  where
    at i j = xs !! (i - 1) !! (j - 1)
    go l1 l2 r1 r2
      | l1 == l2 = [get (l1 == r1) (n, n - 1), get (l1 == r2) (n - 1, n)]
      | r1 == r2 = [get (r1 == l1) (2, 1), get (r1 == l2) (1, 2)]
      | otherwise = [get True (1, 2), get (l1 == r1) (n, n - 1), get (l1 == r2) (n - 1, n)]
    get b x = if b then Just x else Nothing

import Control.Monad
import Data.Char

printPair :: Int -> Int -> IO ()
printPair x y = putStrLn . unwords $ map show [x, y]

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $ do
    n <- read <$> getLine
    a <- replicateM n getLine
    let
      ra = reverse $ map reverse a
      pc = (a !! 0) !! 1
      qc = (a !! 1) !! 0
      xc = (ra !! 0) !! 1
      yc = (ra !! 1) !! 0
      [p, q, x, y] = map (\v -> ord v - ord '0') [pc, qc, xc, yc]
      sw = p + q - x - y
      c = 2 - abs sw
    print c
    when (sw >= 0 && p > 0) (printPair 1 2)
    when (sw >= 0 && q > 0) (printPair 2 1)
    when (sw < 0 && x == 0) (printPair n (n-1))
    when (sw < 0 && y == 0) (printPair (n-1) n)


main = interact $ unlines . map p . chunk 3 . drop 1 . lines

chunk n xs = take n xs : if length xs > n then chunk n (drop n xs) else []

f = (map res [0 ..] !!)
    where res 0 = 0
          res 1 = 0
          res x = minimum [f y + 1 | y <- [x `div` 2..x-1], check y (x-y)]

check :: Int -> Int -> Bool
check y d = or [y `div` a == d | a <- reverse [(y `div` (d+1))..y `div` d], a > 0]

p xs =
    let ((n : k : _) : bs : cs : _) = fmap (fmap read . words) xs :: [[Int]]
        costs = [f x | x <- bs]
        maxk = sum costs + 1
        in show $ last $ dpIters n (dpIter costs cs) $ replicate (minimum [maxk, k+1]) 0

dpIters n f val = foldl (\s e -> e s) val [f x | x <- [0..n-1]]

dpIter costs cs i res = let cost = costs !! i
                            score = cs !! i
                        in g cost score res

zipWith' f l1 l2 = [ f e1 e2 | (e1, e2) <- zipWith k l1 l2 ]
            where
                k x y = x `seq` y `seq` (x,y)

g cost score res = take cost res ++ zipWith' (\ x y -> if (y + score) > x then y + score else x) (drop cost res) res

import Data.Array
import Control.Monad (replicateM_, foldM)
import Data.Array.ST
import Control.Monad.ST (ST, runST)
main = read <$> getLine >>= flip replicateM_ (scase $ minOpsGen 1000)
scase costs = rln >>=
              \[n, k] -> rln >>=
              \bs -> rln >>=
              \cs -> print $
                     maxCoins (min k (12*n)) costs (listArray (1, n) bs)
                     (listArray (1, n) cs)
  where rln = map read . words <$> getLine
minOpsGen :: Int -> Array Int Int
minOpsGen n = let m = n
                  aS = newArray (1, n) m  :: ST s (STArray s Int Int)
              in
                runSTArray $
                aS >>=
                \a -> writeArray a 1 0 >>
                      foldM f a [(i, i + i `div` j) | i <- [1..n], j <- [1..i],
                                  i+div i j <= n]
  where f :: STArray s Int Int -> (Int, Int) -> ST s (STArray s Int Int)
        f a (from, to) = readArray a from >>=
                         \af -> readArray a to >>=
                         \at -> if af + 1 < at
                                then writeArray a to (af+1) >> return a
                                else return a
maxCoins :: Int -> Array Int Int -> Array Int Int -> Array Int Int -> Int
maxCoins k costs b c = knapsack01 k (fmap (costs!) b) c
knapsack01 :: Int -> Array Int Int -> Array Int Int -> Int
knapsack01 wt wa va =
  let (1, n) = bounds wa
  in runST $
     (newArray ((0, 0), (n, wt)) 0 :: ST s (STUArray s (Int, Int) Int)) >>=
     \m -> foldM f m (range ((1, 0), (n, wt))) >>= flip readArray (n, wt)
  where f ::STUArray s (Int, Int) Int -> (Int, Int)
          -> ST s (STUArray s (Int, Int) Int)
        f m (i, w) =  readArray m (i-1, w) >>=
                      \mi1w -> ( if (wa!i) > w
                                  then writeArray m (i, w) mi1w
                                  else readArray m (i-1, w - wa!i) >>=
                                       \mi1w1 -> writeArray m (i, w)
                                                 (max mi1w (mi1w1+(va!i)))
                               ) >> return m


{-# OPTIONS_GHC -O2 -optc-O2 #-}
{-# LANGUAGE BangPatterns #-}
module Main where

import Control.Applicative
import Control.Monad
import Control.Monad.State
import Data.Int
import Data.List
import Text.Printf
import qualified Data.ByteString.Lazy.Char8 as L

getCost :: [Int64] -> Int -> Int64
getCost as k = c
    where ! k' = fromIntegral k
          combine a i = a + i * k'
          candidates = take k . sort $ zipWith combine as ([1 ..] :: [Int64])
          ! c = sum candidates

solve :: [Int64] -> Int64 -> (Int, Int64)
solve as s | s >= cmax = (n, cmax)
           | otherwise = go 0 n
    where n = length as
          cmax = getCost as n

          go l r | l + 1 == r = (l, c)
                 | s >= c = go m r
                 | otherwise = go l m
              where m = (l + r) `div` 2
                    c = getCost as m

type Tokenizer = State [L.ByteString]

nextInt :: Tokenizer Int
nextInt = state $ \(s:ss) -> case L.readInt s of
                               Just (x, _) -> (x, ss)
                               Nothing -> error $ "Can't parse Int from: " ++ (L.unpack s)

nextInt64 :: Tokenizer Int64
nextInt64 = fromIntegral <$> nextInt

go :: Tokenizer (Int, Int64)
go = do
  n <- nextInt
  s <- nextInt64
  as <- replicateM n nextInt64
  return $ solve as s

main :: IO ()
main = do
  input <- L.words <$> L.getContents
  let (k, c) = evalState go input
  printf "%d %d\n" k c

{-# LANGUAGE BangPatterns #-}
module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Applicative
import Data.List
import Data.Int

readInt = maybe undefined (fromIntegral . fst) . B.readInt
readInts = (readInt <$>) . B.words

solve :: Int64 -> Int64 -> [Int64] -> (Int64, Int64)
solve s n as = go 0 (n + 1)
  where
    cost k = sum $ take (fromIntegral k) $ sort $ map (\(i, a) -> a + i * k) $ zip [1..] as
    go !l !r
      | r - l > 1 = if c > s then go l m else go m r
      | otherwise = (l, c)
      where
        m = (l + r) `div` 2
        c = cost m

main = do
  n:s:_ <- readInts <$> B.getLine
  as <- readInts <$> B.getLine
  let (k, t) = solve s n as
  putStr $ show k ++ " " ++ show t

{-# OPTIONS_GHC -O2 -optc-O2 #-}
module Main where

import Control.Applicative
import Control.Monad
import Control.Monad.State
import Data.Int
import Data.List
import Text.Printf
import qualified Data.ByteString.Lazy.Char8 as L

getCost :: [Int64] -> Int -> Int64
getCost as k = c
    where k' = fromIntegral k
          combine a i = a + i * k'
          candidates = take k . sort $ zipWith combine as ([1 ..] :: [Int64])
          c = sum candidates

solve :: [Int64] -> Int64 -> (Int, Int64)
solve as s | s >= cmax = (n, cmax)
           | otherwise = go 0 n
    where n = length as
          cmax = getCost as n

          go l r | l + 1 == r = (l, c)
                 | s >= c = go m r
                 | otherwise = go l m
              where m = (l + r) `div` 2
                    c = getCost as m

type Tokenizer = State [L.ByteString]

nextInt :: Tokenizer Int
nextInt = state $ \(s:ss) -> case L.readInt s of
                               Just (x, _) -> (x, ss)
                               Nothing -> error $ "Can't parse Int from: " ++ (L.unpack s)

nextInt64 :: Tokenizer Int64
nextInt64 = fromIntegral <$> nextInt

go :: Tokenizer (Int, Int64)
go = do
  n <- nextInt
  s <- nextInt64
  as <- replicateM n nextInt64
  return $ solve as s

main :: IO ()
main = do
  input <- L.words <$> L.getContents
  let (k, c) = evalState go input
  printf "%d %d\n" k c

module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Applicative
import Data.List
import Data.Int

readInt = maybe undefined (fromIntegral . fst) . B.readInt
readInts = (readInt <$>) . B.words

solve :: Int64 -> Int64 -> [Int64] -> (Int64, Int64)
solve s n as = go 0 (n + 1)
  where
    cost k = sum $ take (fromIntegral k) $ sort $ map (\(i, a) -> a + i * k) $ zip [1..] as
    go l r
      | r - l > 1 = if c > s then go l m else go m r
      | otherwise = (l, c)
      where
        m = (l + r) `div` 2
        c = cost m

main = do
  n:s:_ <- readInts <$> B.getLine
  as <- readInts <$> B.getLine
  let (k, t) = solve s n as
  putStr $ show k ++ " " ++ show t

{-# LANGUAGE BangPatterns #-}
module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Applicative
import Data.List

readInt = maybe undefined fst . B.readInt
readInts = (readInt <$>) . B.words

solve s n as = go 0 (n + 1)
  where
    cost k = sum $ take k $ sort $ map (\(i, a) -> a + i * k) $ zip [1..] as
    go !l !r
      | r - l > 1 = if c > s then go l m else go m r
      | otherwise = (l, c)
      where
        m = (l + r) `div` 2
        c = cost m

main = do
  n:s:_ <- readInts <$> B.getLine
  as <- readInts <$> B.getLine
  let (k, t) = solve s n as
  putStr $ show k ++ " " ++ show t


import Data.Functor
import Data.List (nub, zip4)
import Data.Bits
import Debug.Trace
import Control.Monad.ST

modNum = 1000000007 :: Integer

modIt :: Integer -> Integer
modIt a = mod a modNum

(//) = div
(%%) = mod
(/|) :: Integer -> Integer -> Bool
a /| b = mod b a == 0

(***) :: Integer -> Integer -> Integer
a *** b = modIt $ a * b

(^^^) :: Integer -> Integer -> Integer
a ^^^ 0 = 1
a ^^^ b = cur *** ((a *** a) ^^^ (div b 2))
    where cur = if b .&. 1 == 1 then a else 1

extGCD :: Integer -> Integer -> (Integer, Integer, Integer)
extGCD a 0 = (a, 1, 0)
extGCD a b = (d, ny, nx - (a // b) * ny)
    where (d, nx, ny) = extGCD b (a %% b)

main :: IO ()
main = getInts >>= putStrLn . show . solve . parsePairs . tail where
    getInts = map read <$> words <$> getContents
    parsePairs [] = []
    parsePairs (x:y:rs) = (x,y) : parsePairs rs

---------------------------------------------------------------------
solve :: [Pair] -> Integer
solve (p:[]) = fst p
solve (p:rs) = case sol of Multi (i, _) (_, _) -> answer i
                           Single (i, _) -> answer i
                           All -> answer 0
                           None -> -1
    where sol = foldl intersect All . map projToX $ map (solve0 p) rs
          answer i = (fst p) *** ((snd p) ^^^ i)

-- (a1,b1), (a2,b2) -> (i,j) s.t. a1*b1^i = a2*b2^j
solve0 :: Pair -> Pair -> Solution
solve0 (a1, b1) (a2, b2) = ans
    where primes = nub . concat . map factorize $ [a1, a2, b1, b2]
          [a1', b1', a2', b2'] = map (toVec primes) [a1, b1, a2, b2]
          f' (x1, y1, x2, y2) = f (x1, x2) (y1, y2)
          ans = foldl intersect All . map f' $ zip4 a1' b1' a2' b2'

factorize :: Integer -> [Integer]
factorize 1 = []
factorize n = let xs = filter (/| n) [2 .. floor . sqrt $ fromIntegral n] in
    if xs == [] then [n] else let x = head xs in x:factorize (n // x)

toVec [] n = []
toVec (p:rs) n = getNum p n : toVec rs n where
    getNum p n = if p /| n then 1 + getNum p (n // p) else 0

---------------------------------------------------------------------
-- (a1,a2), (b1,b2) -> (i,j) s.t. a1+b1*i = a2+b2*j
-- a, b -> t=(i,j) s.t. a+bt is on line x=y
f :: Pair -> Pair -> Solution
f (a1, a2) (0, 0) = if a1 == a2 then All else None
f (a1, a2) (0, b2) = let (x, y) = (a1-a2, b2) in
    if mod x y /= 0 || div x y < 0 then None else Multi (0, div x y) (1, 0)
f (a1, a2) (b1, 0) = let (x, y) = (a2-a1, b1) in
    if mod x y /= 0 || div x y < 0 then None else Multi (div x y, 0) (0, 1)
f (a1, a2) (b1, b2) = runST $ do
    (g, i0, j0) <- return $ extGCD b1 b2
    if g /| (a2-a1)
        then do
          d <- return $ (a2 - a1) // g
          (i, j) <- return $ (i0 * d, -j0 * d)
          (di, dj) <- return $ (b2 // g, b1 // g)
          return $ simplify i j di dj
        else return None

---------------------------------------------------------------------
type Pair = (Integer, Integer)

parallel :: Pair -> Pair -> Bool
parallel (x1, y1) (x2, y2) = x1 * y2 == x2 * y1

data Solution = Multi Pair Pair | Single Pair | None | All deriving (Show, Eq)
getSrc (Multi p _) = p
getDir (Multi _ p) = p

projToX :: Solution -> Solution
projToX s = case s of Multi (i, _) (di, _) -> Multi (i, 0) (di, 0)
                      Single (i, _) -> Single (i, 0)
                      None -> None
                      All -> Multi (0, 0) (1, 0)

simplify i0 j0 di dj = Multi (i0'', j0'') (di, dj)
    where
        t1 = max 0 $ max (div (-i0-1) di) (div (-j0-1) dj) + 1
        i0' = i0 + t1 * di
        j0' = j0 + t1 * dj
        t2 = max 0 $ min (div i0 di) (div j0 dj)
        i0'' = i0' - t2 * di
        j0'' = j0' - t2 * dj

contains :: Pair -> Solution -> Bool
contains _ All = True
contains _ None = False
contains p (Single a) = p == a
contains (x, y) (Multi (i, j) (di, dj)) =
    (i<=x && j<=y && parallel (di,dj) (dx,dy) && (v/|u) && (u//v)>=0)
    where (dx, dy) = (x-i, y-j)
          (u, v) = (dx+dy, di+dj)

intersect :: Solution -> Solution -> Solution
intersect None _ = None
intersect _ None = None
intersect a All = a
intersect All a = a
intersect (Single p) a = if contains p a then Single p else None
intersect a (Single p) = if contains p a then Single p else None
intersect m1@(Multi s1 d1) m2@(Multi s2 d2) = if parallel d1 d2 then res1 else res2
    where
        res1 =
            if not (parallel (dx,dy) d1) then None else if tmp == None then None else ans
            where (dx, dy) = (fst s1 - fst s2, snd s1 - snd s2)
                  tmp = if fst d1 > 0 then f (fst s1, fst s2) (fst d1, fst d2)
                                      else f (snd s1, snd s2) (snd d1, snd d2)
                  ((i, _), (di, _)) = (getSrc tmp, getDir tmp)
                  s = (fst s1 + fst d1 * i, snd s1 + snd d1 * i)
                  d = (fst d1 * di, snd d1 * di)
                  ans = Multi s d
        makeLine x1 y1 x2 y2 = (a, b, -(a*x1+b*y1))
            where a = y2 - y1
                  b = x1 - x2
        res2 = if (t/|x0) && (t/|y0) && contains (x,y) m1 && contains (x,y) m2
                 then Single (x, y)
                 else None
            where (a1, b1, c1) = makeLine (fst s1) (snd s1) (fst s1 + fst d1) (snd s1 + snd d1)
                  (a2, b2, c2) = makeLine (fst s2) (snd s2) (fst s2 + fst d2) (snd s2 + snd d2)
                  t = a1*b2-a2*b1
                  x0 = b1*c2-c1*b2
                  y0 = c1*a2-a1*c2
                  (x, y) = (x0//t, y0//t)

import Data.Functor
import Data.List (nub, zip4)
import Data.Bits
import Debug.Trace
import Control.Monad.ST

modNum = 1000000007 :: Integer

modIt :: Integer -> Integer
modIt a = mod a modNum

(//) = div
(%%) = mod
(/|) :: Integer -> Integer -> Bool
a /| b = mod b a == 0

(***) :: Integer -> Integer -> Integer
a *** b = modIt $ a * b

(^^^) :: Integer -> Integer -> Integer
a ^^^ 0 = 1
a ^^^ b = cur *** ((a *** a) ^^^ (div b 2))
    where cur = if b .&. 1 == 1 then a else 1

extGCD :: Integer -> Integer -> (Integer, Integer, Integer)
extGCD a 0 = (a, 1, 0)
extGCD a b = (d, ny, nx - (a // b) * ny)
    where (d, nx, ny) = extGCD b (a %% b)

main :: IO ()
main = getInts >>= putStrLn . show . solve . parsePairs . tail where
    getInts = map read <$> words <$> getContents
    parsePairs [] = []
    parsePairs (x:y:rs) = (x,y) : parsePairs rs

---------------------------------------------------------------------
solve :: [Pair] -> Integer
solve (p:[]) = fst p
solve (p:rs) = case sol of Multi (i, _) (_, _) -> answer i
                           Single (i, _) -> answer i
                           All -> answer 0
                           None -> -1
    where sol = foldl intersect All . map projToX $ map (solve0 p) rs
          answer i = (fst p) *** ((snd p) ^^^ i)

-- (a1,b1), (a2,b2) -> (i,j) s.t. a1*b1^i = a2*b2^j
solve0 :: Pair -> Pair -> Solution
solve0 (a1, b1) (a2, b2) = ans
    where primes = nub . concat . map factorize $ [a1, a2, b1, b2]
          [a1', b1', a2', b2'] = map (toVec primes) [a1, b1, a2, b2]
          f' (x1, y1, x2, y2) = f (x1, x2) (y1, y2)
          ans = foldl intersect All . map f' $ zip4 a1' b1' a2' b2'

factorize :: Integer -> [Integer]
factorize 1 = []
factorize n = let xs = filter (/| n) [2 .. floor . sqrt $ fromIntegral n] in
    if xs == [] then [n] else let x = head xs in x:factorize (n // x)

toVec [] n = []
toVec (p:rs) n = getNum p n : toVec rs n where
    getNum p n = if p /| n then 1 + getNum p (n // p) else 0

---------------------------------------------------------------------
-- (a1,a2), (b1,b2) -> (i,j) s.t. a1+b1*i = a2+b2*j
-- a, b -> t=(i,j) s.t. a+bt is on line x=y
f :: Pair -> Pair -> Solution
f (a1, a2) (0, 0) = if a1 == a2 then All else None

f (a1, a2) (0, b2) = let (x, y) = (a1-a2, b2) in
    if mod x y /= 0 || div x y < 0 then None else Multi (0, div x y) (1, 0)

f (a1, a2) (b1, 0) = let (x, y) = (a2-a1, b1) in
    if mod x y /= 0 || div x y < 0 then None else Multi (div x y, 0) (0, 1)

f (a1, a2) (b1, b2) = let (g, i0, j0) = extGCD b1 b2 in
    if g /| (a2-a1)
        then let d = (a2-a1)//g
                 (i, j, di, dj) = (i0*d, -j0*d, b2//g, b1//g)
             in simplify i j di dj
        else None

---------------------------------------------------------------------
type Pair = (Integer, Integer)

parallel :: Pair -> Pair -> Bool
parallel (x1, y1) (x2, y2) = x1 * y2 == x2 * y1

data Solution = Multi Pair Pair | Single Pair | None | All deriving (Show, Eq)
getMulti (Multi (i,j) (di,dj)) = (i, j, di, dj)

projToX :: Solution -> Solution
projToX s = case s of Multi (i, _) (di, _) -> Multi (i, 0) (di, 0)
                      Single (i, _) -> Single (i, 0)
                      None -> None
                      All -> Multi (0, 0) (1, 0)

simplify i0 j0 di dj = Multi (i0'', j0'') (di, dj)
    where
        t1 = max 0 $ max (div (-i0-1) di) (div (-j0-1) dj) + 1
        i0' = i0 + t1 * di
        j0' = j0 + t1 * dj
        t2 = max 0 $ min (div i0 di) (div j0 dj)
        i0'' = i0' - t2 * di
        j0'' = j0' - t2 * dj

contains :: Pair -> Solution -> Bool
contains _ All = True
contains _ None = False
contains p (Single a) = p == a
contains (x, y) (Multi (i, j) (di, dj)) =
    (i<=x && j<=y && parallel (di,dj) (dx,dy) && (v/|u) && (u//v)>=0)
    where (dx, dy) = (x-i, y-j)
          (u, v) = (dx+dy, di+dj)

intersect :: Solution -> Solution -> Solution
intersect None _ = None
intersect _ None = None
intersect a All = a
intersect All a = a
intersect (Single p) a = if contains p a then Single p else None
intersect a (Single p) = if contains p a then Single p else None
intersect m1@(Multi s1 d1) m2@(Multi s2 d2) = if parallel d1 d2 then res1 else res2
    where
        res1 = let (dx, dy) = (fst s1 - fst s2, snd s1 - snd s2) in
            if not (parallel (dx,dy) d1)
                then None
                else let tmp = if fst d1 > 0 then f (fst s1, fst s2) (fst d1, fst d2)
                                             else f (snd s1, snd s2) (snd d1, snd d2)
                     in if tmp == None
                          then None
                          else let (i, _, di, _) = getMulti tmp
                                   s = (fst s1 + fst d1 * i, snd s1 + snd d1 * i)
                                   d = (fst d1 * di, snd d1 * di)
                               in Multi s d
        makeLine x1 y1 x2 y2 = (a, b, -(a*x1+b*y1))
            where a = y2 - y1
                  b = x1 - x2
        res2 = if (t/|x0) && (t/|y0) && contains (x,y) m1 && contains (x,y) m2
                 then Single (x, y)
                 else None
            where (a1, b1, c1) = makeLine (fst s1) (snd s1) (fst s1 + fst d1) (snd s1 + snd d1)
                  (a2, b2, c2) = makeLine (fst s2) (snd s2) (fst s2 + fst d2) (snd s2 + snd d2)
                  t = a1*b2-a2*b1
                  x0 = b1*c2-c1*b2
                  y0 = c1*a2-a1*c2
                  (x, y) = (x0//t, y0//t)

import Data.Functor
import Data.List (nub, zip4)
import Data.Bits
import Debug.Trace

modNum = 1000000007 :: Integer

modIt :: Integer -> Integer
modIt a = mod a modNum

(//) = div
(%%) = mod
(/|) :: Integer -> Integer -> Bool
a /| b = mod b a == 0

(***) :: Integer -> Integer -> Integer
a *** b = modIt $ a * b

(^^^) :: Integer -> Integer -> Integer
a ^^^ 0 = 1
a ^^^ b = cur *** ((a *** a) ^^^ (div b 2))
    where cur = if b .&. 1 == 1 then a else 1

extGCD :: Integer -> Integer -> (Integer, Integer, Integer)
extGCD a 0 = (a, 1, 0)
extGCD a b = (d, ny, nx - (a // b) * ny)
    where (d, nx, ny) = extGCD b (a %% b)

main :: IO ()
main = getInts >>= putStrLn . show . solve . parsePairs . tail where
    getInts = map read <$> words <$> getContents
    parsePairs [] = []
    parsePairs (x:y:rs) = (x, y) : parsePairs rs
--main = putStrLn . show $ modPow (123::Integer) (321::Integer)
--main = putStrLn . show $ factorize (modNum::Integer)

---------------------------------------------------------------------
solve :: [Pair] -> Integer
solve (p:[]) = fst p
solve (p:rs) = case sol of Multi (i, _) (_, _) -> answer i
                           Single (i, _) -> answer i
                           All -> answer 0
                           None -> -1
    where sol = foldl intersect All . map projToX $ map (solve0 p) rs
          answer i = (fst p) *** ((snd p) ^^^ i)

-- (a1,b1), (a2,b2) -> (i,j) s.t. a1*b1^i = a2*b2^j
solve0 :: Pair -> Pair -> Solution
solve0 (a1, b1) (a2, b2) =
    --trace ("go " ++ show (a1,b1) ++ " " ++ show (a2,b2) ++ " " ++ show ans) $
        ans
    where primes = nub . concat . map factorize $ [a1, a2, b1, b2]
          [a1', b1', a2', b2'] = map (toVec primes) [a1, b1, a2, b2]
          f' (x1, y1, x2, y2) = f (x1, x2) (y1, y2)
          ans = foldl intersect All . map f' $ zip4 a1' b1' a2' b2'

factorize :: Integer -> [Integer]
factorize 1 = []
factorize n = let xs = filter (/| n) [2 .. floor . sqrt $ fromIntegral n] in
    if xs == [] then [n] else let x = head xs in x:factorize (n // x)

toVec [] n = []
toVec (p:rs) n = getNum p n : toVec rs n where
    getNum p n = if p /| n then 1 + getNum p (n // p) else 0

---------------------------------------------------------------------
-- (a1,a2), (b1,b2) -> (i,j) s.t. a1+b1*i = a2+b2*j
-- a, b -> t=(i,j) s.t. a+bt is on line x=y
f :: Pair -> Pair -> Solution
f (a1, a2) (0, 0) = if a1 == a2 then All else None
f (a1, a2) (0, b2) = let (x, y) = (a1-a2, b2) in
    if mod x y /= 0 || div x y < 0 then None else Multi (0, div x y) (1, 0)
f (a1, a2) (b1, 0) = let (x, y) = (a2-a1, b1) in
    if mod x y /= 0 || div x y < 0 then None else Multi (div x y, 0) (0, 1)
f (a1, a2) (b1, b2) =
    --trace ("f " ++ show (g,i0',j0',i0,j0,di,dj) ++ " "++ show (a1,a2) ++ " " ++ show (b1,b2) ++ " " ++ show ans) $
    ans
    where (g, i0', j0'') = extGCD b1 b2
          j0' = -j0''
          d = (a2 - a1) // g
          (i0, j0) = (i0' * d, j0' * d)
          (di, dj) = (b2 // g, b1 // g)
          val = simplify i0 j0 di dj
          ans = if g /| (a2-a1) then val else None

---------------------------------------------------------------------
type Pair = (Integer, Integer)

parallel :: Pair -> Pair -> Bool
parallel (x1, y1) (x2, y2) = x1 * y2 == x2 * y1

data Solution = Multi Pair Pair | Single Pair | None | All deriving (Show, Eq)
getSrc (Multi p _) = p
getDir (Multi _ p) = p

projToX :: Solution -> Solution
projToX s = case s of Multi (i, _) (di, _) -> Multi (i, 0) (di, 0)
                      Single (i, _) -> Single (i, 0)
                      None -> None
                      All -> Multi (0, 0) (1, 0)

simplify i0 j0 di dj = Multi (i0'', j0'') (di, dj)
    where
        t1 = max 0 $ max (div (-i0-1) di) (div (-j0-1) dj) + 1
        i0' = i0 + t1 * di
        j0' = j0 + t1 * dj
        t2 = max 0 $ min (div i0 di) (div j0 dj)
        i0'' = i0' - t2 * di
        j0'' = j0' - t2 * dj

contains :: Pair -> Solution -> Bool
contains _ All = True
contains _ None = False
contains p (Single a) = p == a
contains (x, y) (Multi (i, j) (di, dj)) =
    (i<=x && j<=y && parallel (di,dj) (dx,dy) && (v/|u) && (u//v)>=0)
    where (dx, dy) = (x-i, y-j)
          (u, v) = (dx+dy, di+dj)

intersect :: Solution -> Solution -> Solution
intersect None _ = None
intersect _ None = None
intersect a All = a
intersect All a = a
intersect (Single p) a = if contains p a then Single p else None
intersect a (Single p) = if contains p a then Single p else None
intersect m1@(Multi s1 d1) m2@(Multi s2 d2) = if parallel d1 d2 then res1 else res2
    where
        res1 =
            if not (parallel (dx,dy) d1) then None else if tmp == None then None else ans
            where (dx, dy) = (fst s1 - fst s2, snd s1 - snd s2)
                  tmp = if fst d1 > 0 then f (fst s1, fst s2) (fst d1, fst d2)
                                      else f (snd s1, snd s2) (snd d1, snd d2)
                  ((i, _), (di, _)) = (getSrc tmp, getDir tmp)
                  s = (fst s1 + fst d1 * i, snd s1 + snd d1 * i)
                  d = (fst d1 * di, snd d1 * di)
                  ans = Multi s d
        makeLine x1 y1 x2 y2 = (a, b, -(a*x1+b*y1))
            where a = y2 - y1
                  b = x1 - x2
        res2 =
            --trace ("res2: " ++ show (x,y)) $
            if (t/|x0) && (t/|y0) && contains (x,y) m1 && contains (x,y) m2
                 then Single (x, y)
                 else None
            where (a1, b1, c1) = makeLine (fst s1) (snd s1) (fst s1 + fst d1) (snd s1 + snd d1)
                  (a2, b2, c2) = makeLine (fst s2) (snd s2) (fst s2 + fst d2) (snd s2 + snd d2)
                  t = a1*b2-a2*b1
                  x0 = b1*c2-c1*b2
                  y0 = c1*a2-a1*c2
                  (x, y) = (x0//t, y0//t)

import Data.Functor
import Data.List (nub, zip4)
import Data.Bits
import Debug.Trace
import Control.Monad.ST

modNum = 1000000007 :: Integer

modIt :: Integer -> Integer
modIt a = mod a modNum

(//) = div
(%%) = mod
(/|) :: Integer -> Integer -> Bool
a /| b = mod b a == 0

(***) :: Integer -> Integer -> Integer
a *** b = modIt $ a * b

(^^^) :: Integer -> Integer -> Integer
a ^^^ 0 = 1
a ^^^ b = cur *** ((a *** a) ^^^ (div b 2))
    where cur = if b .&. 1 == 1 then a else 1

extGCD :: Integer -> Integer -> (Integer, Integer, Integer)
extGCD a 0 = (a, 1, 0)
extGCD a b = (d, ny, nx - (a // b) * ny)
    where (d, nx, ny) = extGCD b (a %% b)

main :: IO ()
main = getInts >>= putStrLn . show . solve . parsePairs . tail where
    getInts = map read <$> words <$> getContents
    parsePairs [] = []
    parsePairs (x:y:rs) = (x,y) : parsePairs rs

---------------------------------------------------------------------
solve :: [Pair] -> Integer
solve (p:[]) = fst p
solve (p:rs) = case sol of Multi (i, _) (_, _) -> answer i
                           Single (i, _) -> answer i
                           All -> answer 0
                           None -> -1
    where sol = foldl intersect All . map projToX $ map (solve0 p) rs
          answer i = (fst p) *** ((snd p) ^^^ i)

-- (a1,b1), (a2,b2) -> (i,j) s.t. a1*b1^i = a2*b2^j
solve0 :: Pair -> Pair -> Solution
solve0 (a1, b1) (a2, b2) = ans
    where primes = nub . concat . map factorize $ [a1, a2, b1, b2]
          [a1', b1', a2', b2'] = map (toVec primes) [a1, b1, a2, b2]
          f' (x1, y1, x2, y2) = f (x1, x2) (y1, y2)
          ans = foldl intersect All . map f' $ zip4 a1' b1' a2' b2'

factorize :: Integer -> [Integer]
factorize 1 = []
factorize n = let xs = filter (/| n) [2 .. floor . sqrt $ fromIntegral n] in
    if xs == [] then [n] else let x = head xs in x:factorize (n // x)

toVec [] n = []
toVec (p:rs) n = getNum p n : toVec rs n where
    getNum p n = if p /| n then 1 + getNum p (n // p) else 0

---------------------------------------------------------------------
-- (a1,a2), (b1,b2) -> (i,j) s.t. a1+b1*i = a2+b2*j
-- a, b -> t=(i,j) s.t. a+bt is on line x=y
f :: Pair -> Pair -> Solution
f (a1, a2) (0, 0) = if a1 == a2 then All else None
f (a1, a2) (0, b2) = let (x, y) = (a1-a2, b2) in
    if mod x y /= 0 || div x y < 0 then None else Multi (0, div x y) (1, 0)
f (a1, a2) (b1, 0) = let (x, y) = (a2-a1, b1) in
    if mod x y /= 0 || div x y < 0 then None else Multi (div x y, 0) (0, 1)
f (a1, a2) (b1, b2) =
    if g /| (a2-a1)
        then let d = (a2-a1)//g
                 (i, j, di, dj) = (i0*d, -j0*d, b2//g, b1//g)
             in simplify i j di dj
        else None
    where (g, i0, j0) = extGCD b1 b2

---------------------------------------------------------------------
type Pair = (Integer, Integer)

parallel :: Pair -> Pair -> Bool
parallel (x1, y1) (x2, y2) = x1 * y2 == x2 * y1

data Solution = Multi Pair Pair | Single Pair | None | All deriving (Show, Eq)
getSrc (Multi p _) = p
getDir (Multi _ p) = p

projToX :: Solution -> Solution
projToX s = case s of Multi (i, _) (di, _) -> Multi (i, 0) (di, 0)
                      Single (i, _) -> Single (i, 0)
                      None -> None
                      All -> Multi (0, 0) (1, 0)

simplify i0 j0 di dj = Multi (i0'', j0'') (di, dj)
    where
        t1 = max 0 $ max (div (-i0-1) di) (div (-j0-1) dj) + 1
        i0' = i0 + t1 * di
        j0' = j0 + t1 * dj
        t2 = max 0 $ min (div i0 di) (div j0 dj)
        i0'' = i0' - t2 * di
        j0'' = j0' - t2 * dj

contains :: Pair -> Solution -> Bool
contains _ All = True
contains _ None = False
contains p (Single a) = p == a
contains (x, y) (Multi (i, j) (di, dj)) =
    (i<=x && j<=y && parallel (di,dj) (dx,dy) && (v/|u) && (u//v)>=0)
    where (dx, dy) = (x-i, y-j)
          (u, v) = (dx+dy, di+dj)

intersect :: Solution -> Solution -> Solution
intersect None _ = None
intersect _ None = None
intersect a All = a
intersect All a = a
intersect (Single p) a = if contains p a then Single p else None
intersect a (Single p) = if contains p a then Single p else None
intersect m1@(Multi s1 d1) m2@(Multi s2 d2) = if parallel d1 d2 then res1 else res2
    where
        res1 =
            if not (parallel (dx,dy) d1) then None else if tmp == None then None else ans
            where (dx, dy) = (fst s1 - fst s2, snd s1 - snd s2)
                  tmp = if fst d1 > 0 then f (fst s1, fst s2) (fst d1, fst d2)
                                      else f (snd s1, snd s2) (snd d1, snd d2)
                  ((i, _), (di, _)) = (getSrc tmp, getDir tmp)
                  s = (fst s1 + fst d1 * i, snd s1 + snd d1 * i)
                  d = (fst d1 * di, snd d1 * di)
                  ans = Multi s d
        makeLine x1 y1 x2 y2 = (a, b, -(a*x1+b*y1))
            where a = y2 - y1
                  b = x1 - x2
        res2 = if (t/|x0) && (t/|y0) && contains (x,y) m1 && contains (x,y) m2
                 then Single (x, y)
                 else None
            where (a1, b1, c1) = makeLine (fst s1) (snd s1) (fst s1 + fst d1) (snd s1 + snd d1)
                  (a2, b2, c2) = makeLine (fst s2) (snd s2) (fst s2 + fst d2) (snd s2 + snd d2)
                  t = a1*b2-a2*b1
                  x0 = b1*c2-c1*b2
                  y0 = c1*a2-a1*c2
                  (x, y) = (x0//t, y0//t)

import Data.Functor
import Data.List (nub, zip4)
import Data.Bits

modNum = 1000000007 :: Integer

modIt :: Integer -> Integer
modIt a = mod a modNum

(//) = div
(%%) = mod

(***) :: Integer -> Integer -> Integer
a *** b = modIt $ a * b

(^^^) :: Integer -> Integer -> Integer
a ^^^ 0 = 1
a ^^^ b = cur *** ((a *** a) ^^^ (div b 2))
    where cur = if b .&. 1 == 1 then a else 1

(|||) :: Integer -> Integer -> Bool
a ||| b = mod b a == 0

extGCD :: Integer -> Integer -> (Integer, Integer, Integer)
extGCD a 0 = (a, 1, 0)
extGCD a b = (d, ny, nx - (a // b) * ny)
    where (d, nx, ny) = extGCD b (a %% b)

main :: IO ()
main = getInts >>= putStrLn . show . solve . parsePairs . tail where
    getInts = map read <$> words <$> getContents
    parsePairs [] = []
    parsePairs (x:y:rs) = (x, y) : parsePairs rs
--main = putStrLn . show $ modPow (123::Integer) (321::Integer)
--main = putStrLn . show $ factorize (modNum::Integer)

---------------------------------------------------------------------
solve :: [Pair] -> Integer
solve (p:[]) = modIt $ fst p
solve (p:rs) = case sol of Multi (i, _) (_, _) -> answer i
                           Single (i, _) -> answer i
                           All -> answer 0
                           None -> -1
    where sol = foldl intersect All . map projToX $ map (solve0 p) rs
          answer i = modIt $ fst p * ((snd p) ^^^ i)

-- (a1,b1), (a2,b2) -> (i,j) s.t. a1*b1^i = a2*b2^j
solve0 :: Pair -> Pair -> Solution
solve0 (a1, b1) (a2, b2) = foldl intersect All . map f' $ zip4 a1' b1' a2' b2'
    where primes = nub . concat . map factorize $ [a1, a2, b1, b2]
          [a1', b1', a2', b2'] = map (toVec primes) [a1, b1, a2, b2]
          f' (x1, y1, x2, y2) = f (x1, x2) (y1, y2)

factorize :: Integer -> [Integer]
factorize 1 = []
factorize n = let xs = filter (||| n) [2 .. floor . sqrt $ fromIntegral n] in
    if xs == [] then [n] else let x = head xs in x:factorize (n // x)

toVec [] n = []
toVec (p:rs) n = getNum p n : toVec rs n where
    getNum p n = if p ||| n then 1 + getNum p (n // p) else 0

---------------------------------------------------------------------
-- (a1,a2), (b1,b2) -> (i,j) s.t. a1+b1*i = a2+b2*j
-- a, b -> t=(i,j) s.t. a+bt is on line x=y
f :: Pair -> Pair -> Solution
f (a1, a2) (0, 0) = if a1 == a2 then All else None
f (a1, a2) (0, b2) = let (x, y) = (a1-a2, b2) in
    if mod x y /= 0 || div x y < 0 then None else Multi (0, div x y) (1, 0)
f (a1, a2) (b1, 0) = let (x, y) = (a2-a1, b1) in
    if mod x y /= 0 || div x y < 0 then None else Multi (div x y, 0) (0, 1)
f (a1, a2) (b1, b2) = if g ||| (a2-a1) then val else None
    where (g, i0', j0') = extGCD b1 (-b2)
          d = (a2 - a1) // g
          (i0, j0) = (i0' * d, j0' * d)
          (di, dj) = (b2 // g, b1 // g)
          val = simplify i0 j0 di dj

---------------------------------------------------------------------
type Pair = (Integer, Integer)

parallel :: Pair -> Pair -> Bool
parallel (x1, y1) (x2, y2) = x1 * y2 == x2 * y1

data Solution = Multi Pair Pair | Single Pair | None | All
getSrc (Multi p _) = p
getDir (Multi _ p) = p

projToX :: Solution -> Solution
projToX s = case s of Multi (i, _) (di, _) -> Multi (i, 0) (di, 0)
                      Single (i, _) -> Single (i, 0)
                      None -> None
                      All -> Multi (0, 0) (1, 0)

simplify i0 j0 di dj = Multi (i0'', j0'') (di, dj) -- TODO
    where
        t1 = max 0 $ max (div (-i0-1) di) (div (-j0-1) dj) + 1
        i0' = i0 + t1 * di
        j0' = j0 + t1 * dj
        t2 = max 0 $ min (div i0 di) (div j0 dj)
        i0'' = i0' - t2 * di
        j0'' = j0' - t2 * dj

contains :: Pair -> Solution -> Bool
contains _ All = True
contains _ None = False
contains p (Single a) = p == a
contains (x, y) (Multi (i, j) (di, dj)) =
    (i<=x && j<=y && parallel (di,dj) (dx,dy) && (v|||u) && (u//v)>0)
    where (dx, dy) = (x-i, y-j)
          (u, v) = (dx+dy, di+dj)

intersect :: Solution -> Solution -> Solution
intersect None _ = None
intersect _ None = None
intersect a All = a
intersect All a = a
intersect (Single p) a = if contains p a then Single p else None
intersect a (Single p) = if contains p a then Single p else None
intersect m1@(Multi s1 d1) m2@(Multi s2 d2) = if parallel d1 d2 then res1 else res2
    where
        res1 = if not (parallel (dx,dy) d1) then None else ans
            where (dx, dy) = (fst s1 - fst s2, snd s1 - snd s2)
                  tmp = if fst d1 > 0 then f (fst s1, fst s2) (fst d1, fst d2)
                                      else f (snd s1, snd s2) (snd d1, snd d2)
                  ((i, _), (di, _)) = (getSrc tmp, getDir tmp)
                  s = (fst s1 + fst d1 * i, snd s1 + snd d1 * i)
                  d = (fst d1 * di, snd d1 * di)
                  ans = Multi s d
        makeLine x1 y1 x2 y2 = (a, b, -(a*x1+b*y1))
            where a = y2 - y1
                  b = x1 - x2
        res2 = if (t|||x0) && (t|||y0) && contains (x,y) m1 && contains (x,y) m2
                 then Single (x, y)
                 else None
            where (a1, b1, c1) = makeLine (fst s1) (snd s1) (fst s1 + fst d1) (snd s1 + snd d1)
                  (a2, b2, c2) = makeLine (fst s2) (snd s2) (fst s2 + fst d2) (snd s2 + snd d2)
                  t = a1*b2-a2*b1
                  x0 = b1*c2-c1*b2
                  y0 = c1*a2-a1*c2
                  (x, y) = (x0//t, y0//t)


import Control.Applicative
import Control.Monad
import Data.List

onecase = do
		[s,a,b,c]<-map read <$> words <$> getLine ::IO [Integer]
		let x = div s c
		print $ x + (div x a)*b

main = do
		n<-read<$> getLine ::IO Int
		replicateM_ n onecase

{-# LANGUAGE Safe #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE MultiWayIf #-}

import Control.Monad
import Control.Monad.ST.Safe
import Control.Monad.State
import Control.Applicative
import Control.Arrow
import Data.List
import Data.Array
import Data.Array.IO.Safe
import Data.Array.ST.Safe
import Data.IORef
import Data.STRef
import Data.Maybe
import Data.Bits
import Data.Ord
import Data.Ratio
import Data.Int
import Data.Char
import qualified Data.IntMap as IM
import qualified Data.ByteString.Char8 as BS
import qualified Data.Set as Set
import qualified Data.Sequence as Sq
import Data.Tuple
import Data.Function
import Text.Printf
import Numeric

readIntBS = fst . fromJust . BS.readInt

main = do
  t <- readLn :: IO Int
  replicateM_ t $ do
    [s,a,b,c] <- map read . words <$> getLine :: IO [Integer]
    let n = s `div` c
    print $ n + (n`div`a)*b

f::[String]->[String]
f []=[]
f (e:es)=let (n:a:b:c:[])=map read (words e)::[Integer]
             t1=n `div` c
             t2=(t1 `div` a)*b
         in (show (t1+t2)):f es

main = do
       e<-getLine
       es<-getContents
       mapM_ putStrLn $ f (lines es)

count :: Integer -> Integer -> Integer -> Integer -> Integer
count s a b c = n + b*(n `div` a)
  where n = s `div` c

readInt :: String -> Int
readInt s = read s

readInteger :: String -> Integer
readInteger s = read s

readIntegerList :: String -> [Integer]
readIntegerList line = map readInteger $ words line

solve :: IO ()
solve = do
  (s:a:b:c:[]) <- fmap readIntegerList getLine
  putStrLn $ show $ count s a b c

main :: IO ()
main = do
  t <- fmap readInt getLine
  sequence_ $ replicate t solve

import Data.Int
main = interact $ unlines . map show . go . map read . tail . words
go [] = []
go (s:a:b:c:xs) = (paid + paid `div` a * b) : go xs where
  paid = s `div` c :: Int64

process :: Integral a => a -> a -> a -> a -> a
process s a b c = d * (a + b) + (m `div` c)
    where (d,m) = divMod s (a*c)

readInt :: String -> Integer
readInt = read

main :: IO ()
main = do
    t <- fmap readInt getLine
    ns <- fmap (map (map readInt.words).lines) getContents
    mapM_ print $ map (\[s,a,b,c] -> process s a b c) ns

import Control.Monad
import Data.Foldable (traverse_)

solve :: [Integer] -> Integer
solve [s, a, b, c] = (s `div` ac) * (a + b) + ((s `mod` ac) `div` c)
	where ac = a * c

main :: IO ()
main = do
	a <- getLine
	tests <- replicateM (read a) getLine
	traverse_ (putStrLn . show .solve) $ map ((map read) . words) tests

import Control.Applicative
import Control.Monad
import Data.List

onecase = do
		[s,a,b,c]<-map read <$> words <$> getLine ::IO [Integer]
		print $ (div s c) + (div s a)*b

main = do
		n<-read<$> getLine ::IO Int
		replicateM_ n onecase


module Main where

import Control.Applicative
import Control.Monad
import Control.Monad.State
import Prelude
import qualified Data.ByteString.Lazy.Char8 as L

type Tokenizer = State [L.ByteString]

nextInt :: Tokenizer Int
nextInt = state $ \(s:ss) -> case L.readInt s of
                                   Just (x, _) -> (x, ss)
                                   Nothing -> error $ "Can't parse Int:" ++ (show s)

nextWord :: Tokenizer [Char]
nextWord = state $ \(s:ss) -> (L.unpack s, ss)

solve :: Tokenizer Int
solve = do
    [n, a, b] <- replicateM 3 nextInt
    s <- nextWord
    if s!!(a - 1) == s!!(b - 1) then return 0
    else return 1

main = do
    contents <- L.getContents
    print $ evalState solve (L.words contents)

main :: IO ()
main = do
  s1 <- getLine
  let [n, a, b] = map read $ words s1
  s <- getLine
  let va = s!!(a - 1)
  let vb = s!!(b - 1)
  if va == vb
    then putStrLn "0"
    else putStrLn "1"

#!/usr/bin/env stack
{- stack
  --resolver lts-2.22
  runghc
  --package array
  --package base
  --package bytestring
  --package containers
  --package mtl
  --package parsec
  --package vector
  --
  -hide-all-packages
-}
{-# LANGUAGE BangPatterns, TupleSections, RankNTypes, ScopedTypeVariables #-}
module Main
( main
) where

import           Prelude hiding (interact, lines, unlines, words, unwords,
                                 sequence, foldr)
import           Data.ByteString.Char8 (pack, unpack, ByteString, lines, words,
                                        unlines, unwords, interact, readInt,
                                        readInteger)
import qualified Data.ByteString.Char8 as BS
import           Data.List (foldl', sort, sortBy, group, groupBy, inits, tails)
import qualified Data.List as L
import qualified Data.IntSet as IS
import           Data.IntSet (IntSet)
import qualified Data.IntMap.Strict as IM
import           Data.IntMap.Strict (IntMap)
import qualified Data.Map.Strict as M
import           Data.Map.Strict (Map)
import qualified Data.Set as S
import           Data.Set (Set)
import qualified Data.Array.IArray as A
import           Data.Array.IArray ((!), Array, listArray, array)
import           Data.Maybe (fromJust, isJust, fromMaybe, maybe, mapMaybe,
                             catMaybes)
import           Data.Either (either)
import           Control.Applicative (Applicative, pure,
                                      (<$>), (<*>), liftA2, liftA3)
import           Control.Monad (unless, when, void, filterM, ap)
import           Control.Arrow ((***), (&&&), first, second)
import           Data.Traversable (sequence, sequenceA, traverse,
                                   Traversable)
import           Data.Ord (comparing, Down(..))
import           Data.Function (on)
import           Data.Bits (complement, xor, (.|.), (.&.), testBit, zeroBits,
                            bit, shiftR, shiftL, Bits)
import qualified Data.Bits as B
import           Data.Word (Word32)
import           Control.Monad.State (State, get, put, gets, modify,
                                      evalState, execState, runState)
import           Text.Parsec (char, space, parse, Parsec)
import qualified Text.Parsec as P
import           Data.Tuple (swap)
import           Data.Foldable (Foldable, foldr)
import           Data.Monoid ((<>), Monoid, mappend, mempty)

type N = Int
toNum = toInt

answer :: N -> N -> [Char] -> N
answer i j xs = if xs !! (i-1) == xs !! (j-1)
                  then 0 else 1

handleInput :: ByteString -> ByteString
handleInput = words & drop 1
            & coerceInput answer
            & show & pack
            -- & map (show & pack) & unlines

toInt = readInt & fromJust & fst
toInte = readInteger & fromJust & fst
toX :: Read a => ByteString -> a
toX = unpack & read

coerceInput f (a:b:c:xs) = f (toNum a) (toNum b) (unpack c)
coerceInput _ _ = error "invalid input"

main :: IO ()
main = interact handleInput

-- Util stuff --
(&) :: (a -> b) -> (b -> c) -> a -> c
(&) = flip (.)
infixl 9 &

module Main where
  import Data.List
  import Control.Monad
  import Data.Array
  import qualified Data.Set as S

  toArray :: [a] -> Array Int a
  toArray xs =
    let ls = length xs - 1
        in array (0, ls) $ zip [0..ls] xs

  readInt :: String -> Int
  readInt s = read s :: Int

  readMultilineInput :: Int -> (String -> IO a) -> IO [a]
  readMultilineInput n transformer = replicateM n (getLine >>= transformer)

  elemSet :: (Ord a) => a -> S.Set a -> Bool
  elemSet elem sets =
    let found = elem `S.lookupIndex` sets
        in toBool found
        where
          toBool :: Maybe Int -> Bool
          toBool (Just _) = True
          toBool Nothing = False

  main :: IO()
  main = do
    [n, a, b] <- getLine >>= return . (map readInt) . words
    xs <- getLine
    let p = xs !! (a - 1)
        q = xs !! (b - 1)
    case p == q of
      True -> print 0
      False -> print 1

module Main where

    main :: IO ()
    main = do
        l <- getLine
        let [_, a, b] = map (\x -> read x :: Int) $ words l
        s <- getLine
        print $ if s !! (a - 1) == s !! (b - 1) then 0 else 1

{-# LANGUAGE FlexibleInstances #-}
module Main (printShit, printShitV, readShit, main, yN, iif) where
import Data.ByteString.Builder
import qualified Data.ByteString.Lazy.Char8 as BS
import Data.Maybe

-- Meat
solve :: Int -> Int -> String -> Int
solve a b s = iif 0 1 (s !! a == s !! b)

-- Shit
main :: IO ()
main = do
        [_,a,b]  <- readShit
        s <- readShit
        printShit $ solve (a - 1) (b - 1) s

class Shit a where
    printShit :: a -> IO ()
    printShitV :: a -> IO ()
    readShit :: IO a
    printShitV = printShit

yN :: Bool -> String
yN True = "YES"
yN False = "NO"

iif :: x -> x -> Bool-> x
iif a b c = if c then a else b

instance  Shit Int where
    printShit = print
    readShit = fmap read getLine

instance  Shit [Int] where
    printShit = putStrLn . unwords . fmap show
    printShitV = putStrLn . unlines . fmap show
    readShit = fmap (fmap read . words) getLine

instance  Shit [Integer] where
    printShit = putStrLn . unwords . fmap show
    printShitV = putStrLn . unlines . fmap show
    readShit = fmap (fmap read . words) getLine

instance Shit [[Int]] where
    printShit = printShit . (fmap.fmap)  (toLazyByteString . integerDec .toInteger)
    readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit

instance Shit [[Double]] where
    printShit = printShit . (fmap.fmap) show
    readShit = fmap (fmap.fmap $ read) readShit

instance Shit [[Integer]] where
    printShit  = printShit . (fmap.fmap)  (toLazyByteString . integerDec)
    readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit

instance Shit String where
    printShit = putStrLn
    printShitV = putStrLn
    readShit = getLine

instance Shit [String] where
    printShit = putStrLn. unwords
    printShitV = putStrLn . unlines
    readShit = fmap lines getContents

instance Shit [[String]] where
    printShit = putStrLn . unlines . fmap unwords
    readShit = fmap (fmap (fmap words) lines) getContents

instance Shit [BS.ByteString] where
    printShit = BS.putStrLn. BS.unwords
    printShitV = BS.putStrLn . BS.unlines
    readShit = fmap BS.lines BS.getContents

instance Shit [[BS.ByteString]] where
    printShit = BS.putStrLn . BS.unlines . fmap BS.unwords
    readShit = fmap (fmap (fmap BS.words) BS.lines) BS.getContents

{-# LANGUAGE FlexibleInstances #-}
module Main (printShit, printShitV, readShit, main, yN, iif) where
import Data.ByteString.Builder
import qualified Data.ByteString.Lazy.Char8 as BS
import Data.Maybe
import Control.Arrow

-- Meat
solve :: Int -> Int -> String -> Int
solve a b s
    | ours == theirs = 0
    | otherwise = findOurs ours . (reverse *** tail) . splitAt b $ s
        where ours = s !! a
              theirs = s !! b

findOurs :: Char -> (String, String) -> Int
findOurs c ([], y:ys) = if c == y then 1  else 1 + findOurs c ([], ys)
findOurs c (x:xs, []) = if c == x then 1 else 1 + findOurs c (xs, [])
findOurs c (x:xs, y:ys) = if c == y || c == x then 1 else 1 + findOurs c (xs, ys)
findOurs _ ([], []) = error "You suck"

-- Shit
main :: IO ()
main = do
        [_,a,b]  <- readShit
        s <- readShit
        printShit $ solve (a - 1) (b - 1) s

class Shit a where
    printShit :: a -> IO ()
    printShitV :: a -> IO ()
    readShit :: IO a
    printShitV = printShit

yN :: Bool -> String
yN True = "YES"
yN False = "NO"

iif :: Bool -> x -> x -> x
iif True a _ = a
iif _ _ b = b

instance  Shit Int where
    printShit = print
    readShit = fmap read getLine

instance  Shit [Int] where
    printShit = putStrLn . unwords . fmap show
    printShitV = putStrLn . unlines . fmap show
    readShit = fmap (fmap read . words) getLine

instance  Shit [Integer] where
    printShit = putStrLn . unwords . fmap show
    printShitV = putStrLn . unlines . fmap show
    readShit = fmap (fmap read . words) getLine

instance Shit [[Int]] where
    printShit = printShit . (fmap.fmap)  (toLazyByteString . integerDec .toInteger)
    readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit

instance Shit [[Double]] where
    printShit = printShit . (fmap.fmap) show
    readShit = fmap (fmap.fmap $ read) readShit

instance Shit [[Integer]] where
    printShit  = printShit . (fmap.fmap)  (toLazyByteString . integerDec)
    readShit = fmap (fmap.fmap $ fromInteger.fst.fromJust. BS.readInteger) readShit

instance Shit String where
    printShit = putStrLn
    printShitV = putStrLn
    readShit = getLine

instance Shit [String] where
    printShit = putStrLn. unwords
    printShitV = putStrLn . unlines
    readShit = fmap lines getContents

instance Shit [[String]] where
    printShit = putStrLn . unlines . fmap unwords
    readShit = fmap (fmap (fmap words) lines) getContents

instance Shit [BS.ByteString] where
    printShit = BS.putStrLn. BS.unwords
    printShitV = BS.putStrLn . BS.unlines
    readShit = fmap BS.lines BS.getContents

instance Shit [[BS.ByteString]] where
    printShit = BS.putStrLn . BS.unlines . fmap BS.unwords
    readShit = fmap (fmap (fmap BS.words) BS.lines) BS.getContents


solve xs = solve' xs []
  where solve' [] ans = ans
        solve' ('x':'y':xs) ans = solve' xs ans
        solve' ('y':'x':xs) ans = solve' xs ans
        solve' (x:xs) [] = solve' xs [x]
        solve' (x:xs) (y:ys)
          | x == y    = solve' xs (x:y:ys)
          | otherwise = solve' xs ys

main = do xs <- getLine
          putStrLn $ solve xs

-- http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html
-- http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-List.html

import Data.List

getAns :: Int -> Char -> String
getAns 0 _ = []
getAns n c = c : getAns (n - 1) c

main :: IO()
main = do
	str <- getLine
	let xlen = length (filter (== 'x') str)
	let ylen = length (filter (== 'y') str)
	if (xlen > ylen)
		then putStrLn (getAns (xlen - ylen) 'x')
		else putStrLn (getAns (ylen - xlen) 'y')

solve l = replicate x 'x' ++ replicate (-x) 'y'
  where x = length (filter (=='x') l) - length (filter (=='y') l)

main = interact $ solve

import qualified Data.ByteString.Char8 as B
import Data.Word

main :: IO ()
main = do l <- B.getLine
          B.putStrLn $ solve l

solve :: B.ByteString -> B.ByteString
solve l = mkStr (B.count 'x' l,B.count 'y' l)

mkStr (x,y)
    | x > y    = B.replicate (x-y) 'x'
    | otherwise = B.replicate (y-x) 'y'

import Data.List
main = do
    str <- getLine
    let (x, y) = partition (\c -> c == 'x') str
        delta = (length x) - (length y)
    putStrLn $ sq $ show (if (delta > 0)
                        then take delta x
                        else take (abs delta) y )

sq :: String -> String
sq s@[c]                     = s
sq ('"':s)  | last s == '"'  = init s
            | otherwise      = s
sq ('\'':s) | last s == '\'' = init s
            | otherwise      = s
sq s                         = s

solve :: String -> String
solve s
  | x <= y  =  replicate (y-x) 'y'
  | otherwise  =  replicate (x-y) 'x'
  where
    x  =  length $ filter (== 'x') s
    y  =  length $ filter (== 'y') s

main :: IO ()
main  =  getLine >>= putStrLn . solve

solve xs = solve' xs []
  where solve' [] ans = reverse ans
        solve' ('x':'y':xs) ans = solve' xs ans
        solve' ('y':'x':xs) ans = solve' xs ans
        solve' (x:xs) [] = solve' xs [x]
        solve' (x:xs) (y:ys)
          | x == y    = solve' xs (x:y:ys)
          | otherwise = solve' xs ys

main = do xs <- getLine
          putStrLn $ solve xs

module Main where

countDiff :: String -> Int
countDiff s = countDiff' s 0
        where
        countDiff' "" d = d
        countDiff' ('x':s) d = countDiff' s (d+1)
        countDiff' ('y':s) d = countDiff' s (d-1)

solve :: String -> String
solve s = if d > 0
          then replicate d 'x'
          else replicate (-d) 'y'
               where
               d = countDiff s

main = getLine >>= (putStrLn . solve)

import qualified Data.ByteString.Char8 as B
main = B.getLine >>= B.putStrLn .solve

solve bs
  | cntx < cnty = B.replicate (cnty-cntx) 'y'
  | otherwise   = B.replicate (cntx-cnty) 'x'
   where
     cntx = B.count 'x' bs
     cnty = B.count 'y' bs

#!/usr/bin/env runghc
main = do
  c <- getContents
  putStrLn . solve . lines $ c

solve (s:ss) = f 0 'x' s
  where
    f 0 a (c:cs) =  f 1 c cs
    f n a []  = replicate n a
    f n a (c:cs) = if c == a then f (n+1) a cs else f (n-1) a cs

main :: IO()
main = do
        l <- getLine
        putStrLn $ func l

func :: String -> String
func l = replicate nc ch
    where
        (nc,ch)=df ( map f ['x','y'])
        f c = length [ x | x <- l, x == c]
        df [nx,ny]
            | nx > ny = ((nx-ny),'x')
            | otherwise = ((ny-nx),'y')

import Data.List
main = interact $ f. map length . group . sort . (++ "xy") where
    f (_:x:y:_)
        | x < y = replicate (y - x) 'y'
        | otherwise = replicate (x - y) 'x'

reduce [] = []
reduce ('y':'x':rest) = reduce rest
reduce ('x':'y':rest) = reduce rest
reduce (x:xs) = x:reduce xs

solve xs = iterate reduce xs !! 250

main = interact solve

import qualified Data.ByteString.Char8 as BS

solve xs = solve' xs []
  where solve' [] ans = ans
        solve' ('x':'y':xs) ans = solve' xs ans
        solve' ('y':'x':xs) ans = solve' xs ans
        solve' (x:xs) [] = solve' xs [x]
        solve' (x:xs) (y:ys)
          | x == y    = solve' xs (x:y:ys)
          | otherwise = solve' xs ys

main = do xs <- fmap BS.unpack BS.getLine
          putStrLn $ solve xs

solve [] = []
solve ('y':'x':rest) = solve rest
solve ('x':'y':rest) = solve rest
solve (x:xs) = x:solve xs

main = interact solve

solve xs = solve' xs []
  where solve' [] ans = reverse ans
        solve' ('x':'y':xs) ans = solve' xs ans
        solve' ('y':'x':xs) ans = solve' xs ans
        solve' (x:xs) [] = solve' xs [x]
        solve' (x:xs) (y:ys)
          | x == y    = solve' xs (x:y:ys)
          | otherwise = solve' xs ys

main = interact solve

#!/usr/bin/env runghc
main = do
  c <- getContents
  putStrLn . solve . lines $ c

solve (s:ss) = f s
  where
    f (a:b:cs) = if a /= b then f cs else a:b:f cs
    f cs = cs


solve [a,b,c] = s a b c 1
  where
   s a b c x | even a && even b =  s (a `div` 2) (b`div`2) c (x*2*2)
             | even a && odd b  =  s (a `div` 2) b c (x*2)
             | odd a  && even b =  s a (b`div`2) c (x*2)
             | odd a  && odd b  =  if x >= c then "YES" else "NO"

main = interact  $ unlines . map ( solve  . map (read :: String -> Int) . words)  . tail . lines

import Control.Monad
import Data.List
import Data.Array

readArray :: Read a => IO [a]
readArray = fmap (map read . words) getLine

readInts :: IO [Integer]
readInts = readArray

readInt :: IO Integer
readInt = readLn

kp2 :: Integer -> Integer
kp2 n
  | n `mod` 2 == 0 = 2 * kp2 (n `div` 2)
  | otherwise = 1

solve :: [Integer] -> String
solve [w, h, n]
  | kp2 w * kp2 h >= n = "YES"
  | otherwise = "NO"

solveCase :: IO String
solveCase = fmap solve readInts

main :: IO ()
main = readLn >>= flip replicateM_ (solveCase >>= putStrLn)

main = interact $ unlines . map (ans . map read . words) . tail . lines

ans [w,h,n]
    | solve (w * h) >= n = "YES"
    | otherwise = "No"

solve = product . (2 <$) . takeWhile even . iterate (`div` 2)

main = interact $ unlines . map (solve . map read . words) . tail . lines

solve [w,h,n]
    | 2 ^ (f w + f h) >= n = "YES"
    | otherwise = "NO"

f x
    | even x = 1 + f (div x 2)
    | otherwise = 0

{-# LANGUAGE Safe #-}
{-# OPTIONS_GHC -O2 #-}

import safe Control.Arrow ((>>>))
import qualified Data.Text as T
import qualified Data.Text.IO as TI
import Data.List
import Data.Function
import Data.Maybe

main :: IO ()
main = TI.getContents >>= (T.lines >>> drop 1 >>> tcio >>> (mapM_ putStrLn)) where
  tcio :: [T.Text] -> [String]
  tcio [] = []
  tcio (nm : rest) = ((:[]). solve . linetois) nm ++ tcio (drop 0 rest)
  linetoi = toi; linetois = (map linetoi).(T.words); linestoiss = map linetois
  --itoline = show; istoline = unwords . (map itoline); isstolines = map istoline
  toi t = toi0 0 t where toi0 n t = if (T.null) t then n else toi0 (10*n + fromIntegral(on (-) fromEnum (T.head t) '0') ) (T.tail t) ;

solve :: [Int] -> String
solve [w,h,n] = if mx2pow w * mx2pow h >=n then "YES" else "NO" where
  mx2pow x = last $ takeWhile (\p->x `mod` p == 0) [2^k | k<-[0..]]

import qualified Data.List as L
import qualified Data.Map as M
import qualified Data.Set as S

import qualified Data.Array as A

import qualified Control.Monad.State.Strict as State
import Control.Monad.ST

import Data.Bits(xor, (.&.), (.|.))
import qualified Data.Array.MArray as MA
import Data.Array.ST(runSTArray, STArray)

import Data.Array((!))
import Control.Monad(replicateM, foldM, mapM, filterM) -- foldM est un foldl
import Data.Maybe

numOcc :: Ord a => [a] -> M.Map a Integer
numOcc (x:xs) = let m = numOcc xs in case M.lookup x m of
	Just i -> M.insert x (i+1) m
	Nothing -> M.insert x 1 m
numOcc [] = M.empty

numOcc' :: A.Ix a => (a, a) -> [a] -> A.Array a Integer
numOcc' size list = runSTArray $ do
	array <- MA.newArray size 0
	foldM (addElem array) () list
	return array

	where
		addElem :: A.Ix a=> STArray s a Integer -> () -> a -> ST s ()
		addElem array action a = do
			i <- MA.readArray array a
			MA.writeArray array a (i+1)

insertWithList :: Ord a => a -> b -> M.Map a [b] -> M.Map a [b]
insertWithList a b m = case M.lookup a m of
	Just l -> M.insert a (b:l) m
	Nothing -> M.insert a [b] m

deleteWithList :: Ord a => a -> M.Map a [b] -> M.Map a [b]
deleteWithList a m = case M.lookup a m of
	Just (x:y:xs) -> M.insert a (y:xs) m
	Just [x] -> M.delete a m

solve :: Integer -> Integer -> Integer -> Bool

solve w h n = (1 + aux w) * (1 + aux h) >= n where
	aux k
		| mod k 2 == 0 = 1 + 2 * aux (div k 2)
		| otherwise = 0

plotResult True = putStrLn "Yes"
plotResult False = putStrLn "No"

main = do
	t <- getLine >>= return . read :: IO Integer
	replicateM (fromInteger t) $ do
		[w, h, n] <- fmap ((fmap read) . words) getLine :: IO [Integer]
		plotResult $ solve w h n

{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE MultiWayIf #-}

import Data.Array
import Data.Char
import Data.List
import Data.Int
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import Control.Applicative
import System.IO
import Data.Bits

-- import qualified Data.Set as Set

readInt :: String -> Int
readInt = read

printArr :: (Show a) => String -> [a] -> IO ()
printArr sep arr = do
    putStrLn . intercalate sep $ (show <$> arr)

print2DArr :: (Show a) => String -> [[a]] -> IO ()
print2DArr sep arr = sequence_ (printArr sep <$> arr)

every n xs = case drop (n-1) xs of
            (y:ys) -> y : every n ys
            [] -> []

yon True = "YES"
yon False = "NO"

main = do
    -- input <- openFile "in" ReadMode
    let input = stdin
    hSetBuffering input (BlockBuffering (Just 4096))
    hSetBuffering stdout (BlockBuffering (Just 4096))
    contents <- hGetContents input
    -- printArr (readIntArr $ head q) " "
    solve contents

solve inp = sequence do
    [x, y, n] <- (readInt <$>) . words <$> tail (lines inp)
    let x' = 1 `shift` countTrailingZeros x
        y' = 1 `shift` countTrailingZeros y
    [putStrLn $ yon (x'*y' >= n)]

module Main where

import Control.Monad
import Data.List
import qualified Data.Set as S

getStrList :: IO [String]
getStrList = words <$> getLine

getIntList :: IO [Int]
getIntList = map read <$> getStrList

printList :: (Show a) => [a] -> IO ()
printList = putStrLn . list2Str

list2Str :: (Show a) => [a] -> String
list2Str = concat . intersperse " " . fmap show

yesOrNo :: Bool -> String
yesOrNo True = "YES"
yesOrNo False = "NO"

tCase :: IO () -> IO ()
tCase x = do
    t <- readLn
    replicateM_ t $ x

main :: IO ()
main = tCase process

--------------------------------------------------------------------------------

process :: IO ()
process = do
    [w, h, n] <- getIntList
    putStrLn $ yesOrNo $ (n <= (f w * f h))

f :: Int -> Int
f x | odd x = 1
    | otherwise = 2 * f (x `div` 2)

count :: Int -> Int
count x | x `mod` 2 == 0 = 1 +  count ( x `div` 2)
        | otherwise = 0

fn :: [Int] -> String
fn x | (2^(count (x!!0)))*(2^(count (x!!1))) >= (x!!2) = "Yes"
     | otherwise = "No"

func::[Int] -> [[Int]]
func [] = []
func x = [take 3 x] ++ func (drop 3 x)
out::[[Int]] -> [String]
out x = [fn y | y <- x]
parsei::String -> [Int]
parsei x = [read k :: Int | k <- tail(words x)]

parseo::[String] -> String
parseo x = concat ([k ++ "\n" | k <- x])
totalfun::String -> String
totalfun x = parseo(out(func(parsei(x))))

main = interact $ totalfun

import Control.Arrow
main = interact $ lines >>> drop 1 >>> map (words >>> map read >>> solve) >>> unlines

solve :: [Int] -> String
solve [w, h, n]
  | ((two (w*h)) >= n) = "YES"
  | otherwise = "NO"

two :: Int -> Int
two x
  | (mod x 2 == 0) = 2 * two (div x 2)
  | otherwise = 1

{-# LANGUAGE DeriveFunctor       #-}
{-# LANGUAGE GADTs               #-}
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE ScopedTypeVariables #-}

import           Control.Arrow              ((>>>))
import           Control.Monad              (MonadPlus (mplus), foldM_, forM_,
                                             join, replicateM_)
import qualified Control.Monad.State.Strict as S
import           Data.Bits
import qualified Data.ByteString.Char8      as B8
import           Data.Char
import           Data.Functor               ((<&>))
import           Data.IORef                 (modifyIORef, newIORef, readIORef)
import           Data.Int
import qualified Data.IntMap                as IM
import           Data.List                  (elemIndices, find, isPrefixOf, nub,
                                             sort, sortOn)
import qualified Data.Map                   as M
import           Data.Maybe                 (fromJust, fromMaybe, isJust)
import qualified Data.Set                   as S
import           Data.Traversable           (forM)
import           GHC.IO.Handle              (hDuplicateTo)
import           System.IO                  (IOMode (ReadMode, WriteMode),
                                             openFile, stdin, stdout)
import           Text.Printf                (printf)

-- import Debug.Trace (trace)
-- debug = flip trace

readIntB8 :: B8.ByteString -> Int
readIntB8 = B8.readInt >>> (fst . fromJust)

readIntegerB8 :: B8.ByteString -> Integer
readIntegerB8 = B8.readInteger >>> (fst . fromJust)

solve :: Int -> Int -> Int -> Bool
solve w h n = cntTwo w h >= n
    where
        cntTwo w h
            | even w    = 2 * cntTwo (w `div` 2) h
            | even h    = 2 * cntTwo w (h `div` 2)
            | otherwise = 1

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        [w, h, n] <- B8.getLine <&> map readIntB8 . B8.words
        let answer = solve w h n
        printf "%s\n" ((if answer then "YES" else "NO")::String)

{-# LANGUAGE
    BangPatterns
  , BlockArguments
  , DataKinds
  , DeriveGeneric
  , DerivingStrategies
  , DerivingVia
  , FlexibleContexts
  , FlexibleInstances
  , GADTs
  , GeneralizedNewtypeDeriving
  , KindSignatures
  , LambdaCase
  , MultiParamTypeClasses
  , MultiWayIf
  , NPlusKPatterns
  , NegativeLiterals
  , OverloadedLabels
  , OverloadedStrings
  , ParallelListComp
  , PolyKinds
  , RankNTypes
  , ScopedTypeVariables
  , StrictData
  , TupleSections
  , TypeApplications
  , TypeFamilies
  , TypeOperators
  , UndecidableInstances
  , ViewPatterns
  #-}

module Main where

import           Control.Applicative
import           Control.Arrow
import           Control.Monad
import           Control.Monad.ST
import qualified Data.ByteString.Char8         as BS
import           Data.Char
import           Data.Foldable
import           Data.Functor
import           Data.Int
import           Data.List
import           Data.Maybe
import           Data.Monoid
import           Data.Ord
import           Data.Semigroup                 ( Max(..)
                                                , Min(..)
                                                , All(..)
                                                , Arg(..)
                                                )
import           Data.Ratio
-- import           Data.Vector.Unboxing.Mutable   ( Unboxable )
-- import qualified Data.Vector.Unboxing.Mutable  as V
import           System.IO
import           Data.Proxy
import           GHC.TypeLits
import           GHC.Generics                   ( Generic )
import           Data.Function
-- import           Data.List.HT                   ( mapAdjacent
--                                                 , isAscending
--                                                 )
-- import           Control.Monad.Primitive        ( PrimMonad(PrimState) )
import qualified Data.Set                      as S
-- import qualified Data.Vector.Algorithms.Radix  as VA
-- import           Text.Parsec.ByteString

-- #if defined(LOCAL_ZER0STAR)
-- {-# ANN module ("Hlint: ignore Unused LANGUAGE pragma" :: String) #-}
-- {-# ANN module ("Hlint: ignore Reduce duplication" :: String) #-}
-- #endif

twice :: (a -> a -> b) -> a -> b
twice f x = f x x

both :: Arrow a => a b c -> a (b, b) (c, c)
both = twice (***)

both2 f (a1, b1) (a2, b2) = (f a1 a2, f b1 b2)

readsLn :: Read a => IO [a]
readsLn = mapM readIO . words =<< getLine

getInt :: IO Int
getInt = fst . fromJust . BS.readInt <$> BS.getLine

getInts :: IO [Int]
getInts = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine

getInteger :: IO Integer
getInteger = fst . fromJust . BS.readInteger <$> BS.getLine

getIntegers :: IO [Integer]
getIntegers = map (fst . fromJust . BS.readInteger) . BS.words <$> BS.getLine

main = do
  t <- getInt
  replicateM_
    t
    do
      [w, h, n] <- getIntegers
      let
        f = toInteger . length . takeWhile ((== 0) . (`mod` 2)) . iterate
          (`div` 2)
        ww = f w
        hh = f h
      putStrLn if 2 ^ (ww + hh) >= n then "Yes" else "No"

import Control.Monad

cont :: Int -> Int
cont = go 1  where
  go x y
    | odd y      = x
    | otherwise  = go (2*x) (div y 2)

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $ do
    [w, h, n] <- map read . words <$> getLine :: IO [Int]
    putStrLn $ if  cont w * cont h >= n
      then  "YES"
      else  "NO"

import Control.Monad
import Data.List
import Data.Array

readArray :: Read a => IO [a]
readArray = fmap (map read . words) getLine

readInts :: IO [Integer]
readInts = readArray

readInt :: IO Integer
readInt = readLn

kp2 :: Integer -> Integer
kp2 n
  | n `mod` 2 == 0 = 1 + kp2 (n `div` 2)
  | otherwise = 1

solve :: [Integer] -> String
solve [w, h, n]
  | kp2 w * kp2 h >= n = "YES"
  | otherwise = "NO"

solveCase :: IO String
solveCase = fmap solve readInts

main :: IO ()
main = readLn >>= flip replicateM_ (solveCase >>= putStrLn)


module Main where

import Data.List (sort, maximum)
import Data.Maybe (fromJust)
import qualified Data.ByteString.Char8 as BS

readNumbers :: IO [Int]
readNumbers =
 (fromJust
  . fmap (map fst)
  . sequence
  . map BS.readInt
  . BS.words) `fmap` BS.getLine

chunks0 _ [] = []
chunks0 n as = (take n as) : chunks0 n (drop n as)

chunks n = filter ((== n) . length) . chunks0 n

getTeamCount k n participants
  | n < 3 = 0
  | otherwise =
      length
        $ filter (<= 5)
        $ map ((+ k) . maximum)
        $ chunks 3 participants

main :: IO ()
main = do
  (n:k:_) <- readNumbers
  participants <- take n `fmap` readNumbers
  print (getTeamCount k n (sort participants))

solve :: String -> String
solve s = show $ quot cnt 3
  where (x:y:xs) = map read (words s)
        cnt = length (filter (\x -> 5 - y >= x) xs)

main = do
  interact solve

-- @betaveros :: vim:set fdm=marker:
{-# LANGUAGE LambdaCase, NPlusKPatterns, TupleSections #-}
{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures #-}
-- import ALL the things! {{{
-- hiding clauses are to allow Data.Foldable's generalizations
import Prelude hiding (mapM, mapM_, sequence, sequence_, foldl, foldl1, foldr, foldr1, and, or, any, all, sum, product, concat, concatMap, maximum, minimum, elem, notElem)
import Control.Applicative
import Control.Arrow
import Control.Exception
import Control.Monad hiding (mapM, mapM_, forM, forM_, sequence, sequence_, msum)
import Control.Monad.ST

import qualified Data.ByteString.Char8 as BS
import Data.ByteString.Char8 (ByteString)
import Data.Bits
import Data.Char
import Data.Either
import Data.Foldable
import Data.Function
import Data.IORef
import Data.List hiding (foldl, foldl', foldl1, foldl1', foldr, foldr1, concat, concatMap, and, or, any, all, sum, product, maximum, minimum, elem, notElem, find)
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.STRef
import Data.String
import Data.Traversable
import Data.Tuple

import qualified Data.Map as Map
import Data.Map (Map)
import qualified Data.Set as Set
import Data.Set (Set)
import qualified Data.Sequence as Seq
import Data.Sequence (Seq, (<|), (|>), (><))

import Debug.Trace
import Text.Printf
import System.IO
-- }}}
-- silly utilities {{{
-- stolen from lens:
a & f = f a
a <&> f = fmap f a
infixl 1 &, <&>

fi :: (Integral a, Num b) => a -> b
fi = fromIntegral
glength :: (Num b) => [a] -> b
glength = genericLength

readInt     = read :: String -> Int
readInteger = read :: String -> Integer
-- (!?) :: (Ord k) => Map k v -> k -> Maybe v
-- (!?) = flip Map.lookup
histogram :: (Ord a, Num b) => [a] -> Map a b
histogram = Map.fromListWith (+) . map (,1)
-- }}}
-- input and output {{{
bsGetLine :: IO ByteString
bsGetLine = fst . BS.spanEnd isSpace <$> BS.getLine

inputInt     = (read <$> getLine) :: IO Int
inputInteger = (read <$> getLine) :: IO Integer
inputDouble  = (read <$> getLine) :: IO Double

inputRow :: (Read a) => IO [a]
inputRow = map read . words <$> getLine
inputInts     = inputRow :: IO [Int]
inputIntegers = inputRow :: IO [Integer]
inputDoubles  = inputRow :: IO [Double]

ssUnwords :: [ShowS] -> ShowS
ssUnwords [] = id
ssUnwords (x:xs) = x . (' ':) . ssUnwords xs

ssUnlines :: [ShowS] -> ShowS
ssUnlines [] = id
ssUnlines (x:xs) = x . ('\n':) . ssUnlines xs

showMany :: (Show a) => [a] -> String
showMany xs = ssUnwords (map shows xs) ""
showMatrix :: (Show a) => [[a]] -> String
showMatrix xs = ssUnlines (map (ssUnwords . map shows) xs) ""

printMany :: (Show a) => [a] -> IO ()
printMany xs = putStrLn (showMany xs)
printMatrix :: (Show a) => [[a]] -> IO ()
printMatrix xs = putStr (showMatrix xs)
-- }}}

main :: IO ()
main = do
	[_,k] <- inputInts
	xs <- inputInts
	print . (`div` 3) . length . filter (<= 5 - k) $ xs

{-# LANGUAGE TupleSections #-}

-- For Input
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
--import qualified Data.ByteString.Lex.Double as BSD
import Data.Char (isSpace)
import Data.IORef
import Text.Printf

-- Data Structure Imports
import Data.Maybe
import Data.List
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map

-- These should be imported by default... :)
import Control.Monad
import Control.Applicative
import Control.Arrow

--------------------------------------------------------------------------------
------------------------------- SOLUTION ---------------------------------------
--------------------------------------------------------------------------------

main :: IO ()
main = do
  all   <- BS.getContents
  input <- newIORef all
  let parse = next input
  (n,k) <- parse int2
  ys <- parse $ intMany n
  let solution = length (filter (\y -> y + k <= 5) ys) `div` 3
  putStrLn $ show solution

--------------------------------------------------------------------------------
-------------------------- IO Function Helpers ---------------------------------
--------------------------------------------------------------------------------

type Parser a = BSC.ByteString -> (a, BSC.ByteString)

int :: Parser Int
int = second (BSC.dropWhile isSpace) . fromJust . BSC.readInt

int2 :: Parser (Int, Int)
int2 = uncurry (first . (,)) . second int . int

int3 :: Parser (Int, Int, Int)
int3 = uncurry (first . (uncurry (,,))) . second int . int2

--double :: Parser Double
--double = second (BSC.dropWhile isSpace) . fromJust . BSD.readDouble

char :: Parser Char
char = BSC.head &&& BSC.tail

letter :: Parser Char
letter = second (BSC.dropWhile isSpace) . char

string :: Parser String
string = (BSC.unpack *** BSC.dropWhile isSpace) . BSC.span (not . isSpace)

readMany :: Parser a -> Int -> Parser [a]
readMany f n bs = first reverse $
                  foldr (\_ (l,bs) -> first (:l) $ f bs) ([],bs) [1..n]

intMany :: Int -> Parser [Int]
intMany = readMany int

next :: IORef BSC.ByteString -> Parser a -> IO a
next input parse = do
  bs <- readIORef input
  let (x, bs') = parse bs
  writeIORef input bs'
  return x

{- CODE JAM input

  cases <- parse int
  forM_ [1..cases] $ \caseNum -> do
         -- Read Data
         -- let solution =
         -- solution <-
         printf "Case #%d: %d\n" caseNum solution
-}

import Control.Applicative
import Data.List

main= do
	[_,k]<-  map read. words <$> getLine ::IO [Int]
	s<- sort.map read.words <$> getLine::IO [Int]
        print $ div (length (takeWhile (<=5-k) s)) 3

import Data.List
main = do
  [n, k] <- getLine >>= return. map read. words :: IO [Int]
  a <- getLine >>= return. filter (< (6 - k)). map read. words :: IO [Int]
  print. (`div` 3). length $ a

import Control.Applicative

main = do
    [n, k] <- map read . words <$> getLine
    ys <- map read . words <$> getLine
    print $ (length $ filter (<= (5-k)) ys) `div` 3

process :: Int -> [Int] -> Int
process k xs = length (filter (\x -> x+k<=5) xs) `div` 3

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    [n,k] <- fmap (map readInt.words) getLine
    ys <- fmap (map readInt.words) getLine
    print $ process k ys

main = do
    [n,k] <- fmap (map read . words) getLine :: IO [Int]
    y <- fmap (map read . words) getLine :: IO [Int]
    print $ (length $ filter (<= 5 - k) y) `div` 3

main = do
    let i=fmap (map read.words) getLine::IO [Int]
    [n,k]<-i
    y<-i
    print $ (length $ filter (<6-k) y) `div` 3

main = getContents >>= print . solve . (map read) . words

solve :: [Int] -> Int
solve (_:k:xs) = flip div 3 $ length $ filter (5-k >= ) xs

import Control.Applicative

main :: IO ()
main=interact solve

solve :: String -> String
solve s = show $ answer k xs
    where (_:k:xs) = read<$>words s

answer :: Int -> [Int] -> Int
answer k xs = quot (sum [1 | i <- xs, k + i <= 5]) 3

import Control.Monad

readListLn :: IO [Int]
readListLn = (map (read :: String -> Int) . words) `liftM` getLine

main :: IO ()
main = do
    [_, k] <- readListLn
    y <- readListLn
    putStr $ show $ length (filter (<=5-k) y) `div` 3

import Data.List
import Data.Function
import Data.Char

main = interact $ show . getAns . map read . words

getAns :: [Int] -> Int
getAns (n:k:xs) = let ns = (length . filter (<=5) . map (+k)) xs
				in ns `div` 3

main = do
  [_, k] <- fmap (map read . words) getLine
  ys <- fmap (map read . words) getLine

  let c = length $ filter (\x -> x + k <= 5) ys
  print $ c `div` 3

main = do
  (n:k:_) <- fmap (map read . words) getLine :: IO [Int]
  nums <- fmap (map read . words) getLine
  let answer = length (filter (\a -> k+a <= 5) nums) `div` 3
  print answer

{-# LANGUAGE OverloadedStrings #-}

import Control.Applicative ((<$>))
import Text.Printf
import Data.Maybe (Maybe, fromMaybe)
import qualified Data.ByteString.Char8 as BS

main :: IO ()
main = do
  [n, k] <- readInts
  y <- readInts
  print . (`div` 3) . length . filter (<= 5 - k) $ y

toNumber = fst . fromMaybe (0, "")
readInt = toNumber . BS.readInt <$> BS.getLine
readInts = (map (toNumber . BS.readInt) <$> (BS.words <$> BS.getLine))

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Data.Functor
import Control.Monad
import Control.Monad.ST.Safe
import Control.Arrow
import Data.Array
import Data.Array.ST.Safe
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString.Char8 as C
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  solve.tail.concat =<< (forM [1..2] $ \i-> map (fst.fromJust.C.readInt).C.words <$> C.getLine)

solve (x:xs) = let l = length $ filter (\a->a+x<=5) xs in print $ l `div` 3

import Control.Applicative
import Data.List (sort)

main = do
  [_, k] <- map read . words <$> getLine
  ss <- sort . map read . words <$> getLine
  let
    f xs
      | length xs < 3 = 0
      | all (<=5) . map (+k) $ take 3 xs = 1 + f (drop 3 xs)
      | otherwise = 0
    in putStrLn . show $ f ss

import Data.List

conv = map (read::String->Int) . words
g k xs = div ((length . sort) [x | x <- xs , 5 - x >= k]) 3

main = do
    i <- getLine
    x <- getLine
    let k = (conv i) !! 1
    let xs = conv x
    putStrLn $ show (g k xs)

import Control.Applicative
import Data.List

main=do
     [n,k]<-    map read <$> words <$> getLine::IO [Int]
     q<-map read <$> words <$> getLine::IO [Int]
     print $ div ( length $ filter (<=5-k) q) 3

main :: IO ()
main = getContents >>= print . solve . map read . words

solve :: [Int] -> Int
solve (_:k:ys) = length (filter (<=5-k) ys) `div` 3
solve _ = undefined

main = interact $ show . solve . map read . words
solve (n:k:ns) = (`div` 3) $ length $ filter (<= 5 - k) ns

import Data.List

strToList = (fmap (read :: (String -> Int))).words

f xs k = (length $ filter (<=5) $ map (+k) xs) `div` 3

main = do

    [n, k] <- fmap strToList getLine

    s <- fmap strToList getLine

    putStrLn $ show $ f s k

import Text.Printf (printf)
import Control.Monad (forM_)

main :: IO ()
main = do
  [n, k] <- fmap (map read . words) getLine :: IO [Int]
  xs <- fmap (map read . words) getLine :: IO [Int]
  print $ length (filter (\x -> x + k <= 5) xs) `div` 3

import Control.Applicative
import Data.List

main=do
     [n,k]<-    map read <$> words <$> getLine::IO [Int]
     q<-map read <$> words <$> getLine::IO [Int]
     print $ div ( length $ takeWhile (>=5-k) q) 3

import Control.Applicative
import Data.List

main=do
     [n,k]<-    map read <$> words <$> getLine::IO [Int]
     q<-map read <$> words <$> getLine::IO [Int]
     print $ div ( length $ takeWhile (<=5-k) q) 3

import Data.List
main = do
  [n, k] <- getLine >>= return. map read. words :: IO [Int]
  a <- getLine >>= return. filter (< (4 - k)). map read. words :: IO [Int]
  print. (`div` 3). length $ a


import Control.Monad

ans = do
 nInput <- getLine
 aInput <- getLine
 mInput <- getLine
 bInput <- getLine
 let n = read nInput :: Int
 let a = words aInput
 let m = read mInput :: Int
 let b = words bInput
 let pos = 1 + sum [read x :: Int | x <- b] `mod` n
 let result = if pos == 0 then a !! (n - 1) else a !! (pos - 1)
 return result

main = do
 tInput <- getLine
 let t = read tInput :: Int
 results <- replicateM t (do ans)
 putStrLn (unwords results)

ans = do
 nInput <- getLine
 aInput <- getLine
 mInput <- getLine
 bInput <- getLine
 let n = read nInput :: Int
 let a = words aInput
 let m = read mInput :: Int
 let b = words bInput
 let pos = 1 + sum [read x :: Int | x <- b] `mod` n
 let result = if pos == 0 then a !! (n - 1) else a !! (pos - 1)
 return result

main = do
 tInput <- getLine
 let t = read tInput :: Int
 results <- sequence (replicate t ans)
 putStrLn (unwords results)

ans = do
 nInput <- getLine
 aInput <- getLine
 mInput <- getLine
 bInput <- getLine
 let n = read nInput :: Int
 let a = words aInput
 let m = read mInput :: Int
 let b = words bInput
 let pos = 1 + sum (map (\x -> read x :: Int) b) `mod` n
 let result = if pos == 0 then a !! (n - 1) else a !! (pos - 1)
 putStrLn result

main = do
 tInput <- getLine
 let t = read tInput :: Int
 let results = replicate t ans
 sequence results

ans = do
 nInput <- getLine
 aInput <- getLine
 mInput <- getLine
 bInput <- getLine
 let n = read nInput :: Int
 let a = words aInput
 let m = read mInput :: Int
 let b = words bInput
 let pos = 1 + sum [read x :: Int | x <- b] `mod` n
 let result = if pos == 0 then a !! (n - 1) else a !! (pos - 1)
 putStrLn result

main = do
 tInput <- getLine
 let t = read tInput :: Int
 let results = replicate t ans
 sequence results

ans = do
 nInput <- getLine
 aInput <- getLine
 mInput <- getLine
 bInput <- getLine
 let n = read nInput :: Int
 let a = words aInput
 let m = read mInput :: Int
 let b = words bInput
 let pos = 1 + sum [read x :: Int | x <- b] `mod` n
 let result = if pos == 0 then a !! (n - 1) else a !! (pos - 1)
 putStrLn result

main = do
 tInput <- getLine
 let t = read tInput :: Int
 let results = [ans | x <- [1 .. t]]
 sequence results

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RecordWildCards #-}

import Control.Applicative (Applicative (liftA2))
import Control.Arrow ((>>>))
import Control.Monad.State (MonadState (get, put), State, evalState, gets, replicateM)
import qualified Data.ByteString.Char8 as C
import Data.Maybe (fromJust)
import Data.Word (Word32)
import GHC.Conc (par, pseq)
import System.Environment (getArgs)

data TC = TC {n :: Int, m :: Int, a :: [Int], b :: [Int]}

aliceBob x = if x then "Alice" else "Bob"

solve TC {..} = a!!p
  where
    p = (sum b) `mod` n

main = C.interact $ runScanner scan >>> map solve >>> map show >>> map C.pack >>> C.unlines

scan =
  numberOf $
    ( do
        n <- int
        a <- n >< int
        m <- int
        b <- m >< int
        pure $ TC n m a b
    )

type Scanner = State [C.ByteString]

runScanner :: Scanner a -> C.ByteString -> a
runScanner = runScannerWith C.words

runScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a
runScannerWith t s = evalState s . t

peek :: Scanner C.ByteString
peek = gets head

str :: Scanner C.ByteString
str = get >>= \case s : ss -> put ss >> return s

int :: Scanner Int
int = fst . fromJust . C.readInt <$> str

integer :: Scanner Integer
integer = read . C.unpack <$> str

double :: Scanner Double
double = read . C.unpack <$> str

decimal :: Int -> Scanner Int
decimal p = round . ((10 ^ p) *) <$> double

numberOf :: Scanner a -> Scanner [a]
numberOf s = int >>= flip replicateM s

many :: Scanner a -> Scanner [a]
many s = get >>= \case [] -> return []; _ -> (:) <$> s <*> many s

till :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]
till p s = do
  t <- peek
  if p t then return [] else (:) <$> s <*> till p s

times :: Int -> Scanner a -> Scanner [a]
times = replicateM

(><) = times

two, three, four :: Scanner a -> Scanner [a]
[two, three, four] = map times [2 .. 4]

pair :: Scanner a -> Scanner b -> Scanner (a, b)
pair = liftA2 (,)