import Control.Applicative
import Data.Function
import Data.List

data Point = Point Double Double deriving (Eq)
data Segment = Segment { segmentStart, segmentEnd :: Point } deriving (Eq)
data Vector = Vector Double Double

getWords = map read . words <$> getLine

splitEvery n = unfoldr $ \xs -> if null xs then Nothing else Just $ splitAt n xs
getPoints = map (\[a, b] -> Point a b) . splitEvery 2 <$> getWords

cross (Vector x1 y1) (Vector x2 y2) = x1*y2 - x2*y1
dot (Vector x1 y1) (Vector x2 y2) = x1*x2 + y1*y2
sub (Point px py) (Point qx qy) = Vector (qx - px) (qy - py)

intersects s@(Segment p1 p2) t@(Segment p3 p4) =
		(d1 > 0 && d2 < 0 || d1 < 0 && d2 > 0) &&
		(d3 > 0 && d4 < 0 || d3 < 0 && d4 > 0) ||
		d1 == 0 && onSegment p1 t ||
		d2 == 0 && onSegment p2 t ||
		d3 == 0 && onSegment p3 s ||
		d4 == 0 && onSegment p4 s
	where
		direction p q r = sub p r `cross` sub p q

		onSegment (Point rx ry) (Segment (Point px py) (Point qx qy)) =
			min px qx <= rx && rx <= max px qx &&
			min py qy <= ry && ry <= max py qy

		d1 = direction p3 p4 p1
		d2 = direction p3 p4 p2
		d3 = direction p1 p2 p3
		d4 = direction p1 p2 p4

data Line = Line Point Point

onLine r (Line p q) = sub p q `cross` sub p r == 0

intersectsRay s@(Segment p1 p2) t@(Segment p3 p4) =
	intersects s t && not (p3 `onLine` (Line p1 p2))

intersection s@(Segment sa sb) t@(Segment ta tb) =
		sa `add` (c `mult` (sa `sub` sb))
	where
		mult a (Vector x y) = Vector (a * x) (a * y)
		add (Point px py) (Vector vx vy) = Point (px + vx) (py + vy)
		c = (sub sa ta `cross` sub ta tb) / (sub sa sb `cross` sub ta tb)

distance (Point px py) (Point qx qy) = sqrt $ (qx - px) ** 2 + (qy - py) ** 2

solve start end polygon
		| length intersecting < 2 = start `distance` end
		| otherwise =
			start `distance` i1 +
			minimum [distThrough, distAround1, distAround2] +
			i2 `distance` end
	where
		startEnd = Segment start end
		segments = zipWith Segment polygon $ tail polygon ++ [head polygon]

		intersecting = filter (startEnd `intersectsRay`) segments
		intersections = map (intersection startEnd) intersecting

		(s1,i1):(s2,i2):_ = sortBy (compare `on` (distance start . snd)) $
				intersecting `zip` intersections

		distThrough = 2 * (i1 `distance` i2)

		distAround s1 s2 segments = sum $ map (\(Segment p q) -> p `distance` q) $
			takeWhile (/= s2) $ tail $ dropWhile (/= s1) $ segments ++ segments

		distAround1 =
			i1 `distance` segmentEnd s1 +
			distAround s1 s2 segments +
			segmentStart s2 `distance` i2

		distAround2 =
			i1 `distance` segmentStart s1 +
			distAround s1 s2 (reverse segments) +
			segmentEnd s2 `distance` i2

main = do
	[start, end] <- getPoints
	_ <- getLine
	polygon <- getPoints
	print $ solve start end polygon

import Control.Applicative
import Data.Function
import Data.List
import Debug.Trace

data Point = Point Double Double deriving (Eq, Show)
data Segment = Segment { segmentStart, segmentEnd :: Point } deriving (Eq, Show)
data Vector = Vector Double Double

getWords = map read . words <$> getLine

splitEvery n = unfoldr $ \xs -> if null xs then Nothing else Just $ splitAt n xs
getPoints = map (\[a, b] -> Point a b) . splitEvery 2 <$> getWords

cross (Vector x1 y1) (Vector x2 y2) = x1*y2 - x2*y1
dot (Vector x1 y1) (Vector x2 y2) = x1*x2 + y1*y2
sub (Point px py) (Point qx qy) = Vector (qx - px) (qy - py)

intersects s@(Segment p1 p2) t@(Segment p3 p4) =
		(d1 > 0 && d2 < 0 || d1 < 0 && d2 > 0) &&
		(d3 > 0 && d4 < 0 || d3 < 0 && d4 > 0) ||
		d1 == 0 && onSegment p1 t ||
		d2 == 0 && onSegment p2 t ||
		d3 == 0 && onSegment p3 s ||
		d4 == 0 && onSegment p4 s
	where
		direction p q r = sub p r `cross` sub p q

		onSegment (Point rx ry) (Segment (Point px py) (Point qx qy)) =
			min px qx <= rx && rx <= max px qx &&
			min py qy <= ry && ry <= max py qy

		d1 = direction p3 p4 p1
		d2 = direction p3 p4 p2
		d3 = direction p1 p2 p3
		d4 = direction p1 p2 p4

data Line = Line Point Point

onLine r (Line p q) = sub p q `cross` sub p r == 0

intersectsRay s@(Segment p1 p2) t@(Segment p3 p4) =
	intersects s t && not (p3 `onLine` (Line p1 p2))

intersection s@(Segment sa sb) t@(Segment ta tb) =
		sa `add` (c `mult` (sa `sub` sb))
	where
		mult a (Vector x y) = Vector (a * x) (a * y)
		add (Point px py) (Vector vx vy) = Point (px + vx) (py + vy)
		c = (sub sa ta `cross` sub ta tb) / (sub sa sb `cross` sub ta tb)

distance (Point px py) (Point qx qy) = sqrt $ (qx - px) ** 2 + (qy - py) ** 2

solve start end polygon
		| length intersecting < 2 = start `distance` end
		| otherwise =
			start `distance` i1 +
			minimum [distThrough, distAround1, distAround2] +
			i2 `distance` end
	where
		startEnd = Segment start end
		segments = zipWith Segment polygon $ tail polygon ++ [head polygon]

		intersecting = filter (startEnd `intersectsRay`) segments
		intersections = map (intersection startEnd) intersecting

		(s1,i1):(s2,i2):_ = sortBy (compare `on` (distance start . snd)) $
				intersecting `zip` intersections

		distThrough = 2 * (i1 `distance` i2)

		distAround s1 s2 segments = sum $ map (\(Segment p q) -> p `distance` q) $
			takeWhile (/= s2) $ tail $ dropWhile (/= s1) $ segments ++ segments

		distAround1 =
			i1 `distance` (segmentEnd s1) +
			(distAround s1 s2 segments) +
			(segmentStart s2) `distance` i2

		distAround2 =
			i1 `distance` (segmentStart s1) +
			(distAround s1 s2 $ reverse segments) +
			(segmentEnd s2) `distance` i2

main = do
	[start, end] <- getPoints
	_ <- getLine
	polygon <- getPoints
	print $ solve start end polygon

import Control.Applicative
import Data.Function
import Data.List

data Point = Point Double Double deriving (Eq)
data Segment = Segment { segmentStart, segmentEnd :: Point } deriving (Eq)
data Vector = Vector Double Double

getWords = map read . words <$> getLine

splitEvery n = unfoldr $ \xs -> if null xs then Nothing else Just $ splitAt n xs
getPoints = map (\[a, b] -> Point a b) . splitEvery 2 <$> getWords

cross (Vector x1 y1) (Vector x2 y2) = x1*y2 - x2*y1
dot (Vector x1 y1) (Vector x2 y2) = x1*x2 + y1*y2
sub (Point px py) (Point qx qy) = Vector (qx - px) (qy - py)

intersects s@(Segment p1 p2) t@(Segment p3 p4) =
		(d1 > 0 && d2 < 0 || d1 < 0 && d2 > 0) &&
		(d3 > 0 && d4 < 0 || d3 < 0 && d4 > 0) ||
		d1 == 0 && onSegment p1 t ||
		d2 == 0 && onSegment p2 t ||
		d3 == 0 && onSegment p3 s ||
		d4 == 0 && onSegment p4 s
	where
		direction p q r = sub p r `cross` sub p q

		onSegment (Point rx ry) (Segment (Point px py) (Point qx qy)) =
			min px qx <= rx && rx <= max px qx &&
			min py qy <= ry && ry <= max py qy

		d1 = direction p3 p4 p1
		d2 = direction p3 p4 p2
		d3 = direction p1 p2 p3
		d4 = direction p1 p2 p4

data Line = Line Point Point

onLine r (Line p q) = sub p q `cross` sub p r == 0

intersectsRay s@(Segment p1 p2) t@(Segment p3 p4) =
	intersects s t && not (p3 `onLine` Line p1 p2)

intersection s@(Segment sa sb) t@(Segment ta tb) =
		sa `add` (c `mult` (sa `sub` sb))
	where
		mult a (Vector x y) = Vector (a * x) (a * y)
		add (Point px py) (Vector vx vy) = Point (px + vx) (py + vy)
		c = (sub sa ta `cross` sub ta tb) / (sub sa sb `cross` sub ta tb)

distance (Point px py) (Point qx qy) = sqrt $ (qx - px) ** 2 + (qy - py) ** 2

solve start end polygon
		| length intersecting < 2 = start `distance` end
		| otherwise =
			start `distance` i1 +
			minimum [distThrough, distAround1, distAround2] +
			i2 `distance` end
	where
		startEnd = Segment start end
		segments = zipWith Segment polygon $ tail polygon ++ [head polygon]

		intersecting = filter (startEnd `intersectsRay`) segments
		intersections = map (intersection startEnd) intersecting

		(s1,i1):(s2,i2):_ = sortBy (compare `on` (distance start . snd)) $
				intersecting `zip` intersections

		distThrough = 2 * (i1 `distance` i2)

		distAround s1 s2 segments = sum $ map (\(Segment p q) -> p `distance` q) $
			takeWhile (/= s2) $ tail $ dropWhile (/= s1) $ segments ++ segments

		distAround1 =
			i1 `distance` segmentEnd s1 +
			distAround s1 s2 segments +
			segmentStart s2 `distance` i2

		distAround2 =
			i1 `distance` segmentStart s1 +
			distAround s1 s2 (reverse segments) +
			segmentEnd s2 `distance` i2

main = do
	[start, end] <- getPoints
	_ <- getLine
	polygon <- getPoints
	print $ solve start end polygon


import Control.Monad (liftM, replicateM)
import Data.Array ((!), listArray)
import Data.Char (ord)
import Data.Graph (buildG, edges, path)
import Data.List (intercalate)

data Query  =  Add Int Int | Path Int Int

solve :: [Query] -> [Bool]
solve qs  =  solve' 1 emptyG qs
  where
    n  =  length $ filter isAdd qs
    segments  =  listArray (1, n) $ filter isAdd qs
    isAdd (Add _ _)  =  True
    isAdd _  =  False
    emptyG  =  buildG (1, 1) []
    solve' k graph []  =  []
    solve' k graph (q:qs)  =  case q of
        (Add a b)  ->  solve' (k+1) graph' qs
        (Path a b)  ->  path graph a b : solve' k graph qs
      where
        graph'  =  buildG (1, k)
            $ edges graph ++ filter intersect ([(i, k) | i <- [1..k-1]] ++ [(k, i) | i <- [1..k-1]])
        intersect (i, j)  =  case (segments ! i, segments ! j) of
            (Add a b, Add c d)  ->  c < a && a < d || c < b && b < d

main :: IO ()
main  =  do
    n  <-  readLn
    qs  <-  replicateM n readQuery
    mapM_ (putStrLn . fromBool) $ solve qs

  where

    fromBool True  =  "YES"
    fromBool False  =  "NO"

    readQuery :: IO Query
    readQuery  =  do
        [q, a, b]  <-  reads
        case q of
            1  ->  return $ Add a b
            2  ->  return $ Path a b

    reads :: Num a => IO [a]
    reads  =  liftM (map read . words) getLine
      where
        read ('-':s)  =  (-1) * read s
        read s  =  read' 0 s
        read' a ""  =  a
        read' a (c:s)  =  read' a' s
          where
            a'  =  10 * a + fromIntegral (ord c - ord '0')

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}

import Control.Applicative
import Control.Monad
import qualified Data.ByteString.Char8 as B
import Data.Array.Base
import Data.Array.IO (IOUArray)

readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n

rep :: Monad m => Int -> (Int -> m ()) -> m ()
rep !n f=go 0 where go !i=when(i<n)$f i>>go(i+1)
{-# INLINE rep #-}

type Vertex = Int

main :: IO ()
main = do
  n <- readLn
  larr <- newArray (0,n-1) minBound :: IO (IOUArray Vertex Int)
  rarr <- newArray (0,n-1) minBound :: IO (IOUArray Vertex Int)
  used <- newArray (0,n-1) False :: IO (IOUArray Vertex Bool)

  let getInterval i = do
        !l <- unsafeRead larr i
        !r <- unsafeRead rarr i
        return $! (l,r)
  let isVertex (l,r) = (l,r) /= minBound
  let dfs v = do
        (l,r) <- getInterval v
        rep n $ \i-> do
          flg <- unsafeRead used i
          unless flg $ do
            (nl,nr) <- getInterval i
            when (((nl<l&&l<nr)||(nl<r&&r<nr)) && isVertex (nl,nr)) $ do
              unsafeWrite used i True
              dfs i
  let query1 i l r = do
       unsafeWrite larr i l
       unsafeWrite rarr i r
  let query2 start goal = do
        rep n $ \i-> unsafeWrite used i False
        unsafeWrite used start True
        dfs start
        res <- unsafeRead used goal
        if res then putStrLn "YES" else putStrLn "NO"
  let solve qs = go 1 qs
         where
           go !i (1:x:y:rest) = query1 i x y >> go (i+1) rest
           go !i (2:a:b:rest) = query2 a b >> go i rest
           go _ _ = return ()
  B.getContents >>= solve.map readInt.B.words

import Control.Monad
import Control.Applicative
import Data.List
import qualified Data.Map as M
import qualified Data.Set as S

main = do
    n <- read <$> getLine
    loop n 1 M.empty

loop :: Int -> Int -> M.Map Int (Int,Int) -> IO ()
loop 0 _ _ = return ()
loop n i m = do
    c:x:y:_ <- map read . words <$> getLine
    case c of
        1 -> loop (n-1) (i+1) (M.insert i (x,y) m)
        2 -> do
            putStrLn $ if hasPath m x y then "YES" else "NO"
            loop (n-1) i m

hasPath m from to =
    let s = snd $ runState (dfs m from) S.empty in
    S.member to s

dfs m pos = do
    memo <- get
    case S.member pos memo of
        True -> return ()
        False -> do
            let l = next (m M.! pos) (M.assocs m)
            put (S.insert pos memo)
            mapM_ (dfs m) l

next :: (Int,Int) -> [(Int,(Int,Int))] -> [Int]
next (a,b) l = do
    (i,(c,d)) <- l
    if (c < a && a < d) ||  (c < b && b < d) then return i else []

newtype State a = State { runState :: S.Set Int -> (a,S.Set Int) }

instance Monad State where
    return x = State (\s -> (x,s))
    m >>= f = State (\s ->
        let (a,s') = runState m s in
        runState (f a) s')

get = State (\s -> (s,s))
put s = State (\_ -> ((),s))

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}

import Control.Applicative
import Control.Monad
import qualified Data.ByteString.Char8 as B
import Data.Array.Base
import Data.Array.IO (IOUArray)

readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n

rep :: Monad m => Int -> (Int -> m ()) -> m ()
rep !n f=go 0 where go !i=when(i<n)$f i>>go(i+1)
{-# INLINE rep #-}

type Vertex = Int

main :: IO ()
main = do
  n <- readLn
  larr <- newArray (0,n-1) minBound :: IO (IOUArray Vertex Int)
  rarr <- newArray (0,n-1) minBound :: IO (IOUArray Vertex Int)
  used <- newArray (0,n-1) False :: IO (IOUArray Vertex Bool)

  let getInterval i = do
        !l <- unsafeRead larr i
        !r <- unsafeRead rarr i
        return $! (l,r)
  let isVertex (l,r) = (l,r) /= minBound
  let dfs v = do
        (l,r) <- getInterval v
        rep n $ \i-> do
          flg <- unsafeRead used i
          unless flg $ do
            (nl,nr) <- getInterval i
            when (((nl<l&&l<nr)||(nl<r&&r<nr)) && isVertex (nl,nr)) $ do
              unsafeWrite used i True
              dfs i
  let query1 i l r = do
       unsafeWrite larr i l
       unsafeWrite rarr i r
  let query2 start goal = do
        rep n $ \i-> unsafeWrite used i False
        unsafeWrite used start True
        dfs start
        res <- unsafeRead used goal
        if res then putStrLn "YES" else putStrLn "NO"
  let solve qs = go 1 qs
         where
           go !i (1:x:y:rest) = query1 i x y >> go (i+1) rest
           go !i (2:a:b:rest) = query2 a b >> go (i+1) rest
           go _ _ = return ()
  B.getContents >>= solve.map readInt.B.words


{-# LANGUAGE CPP #-}
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE DatatypeContexts #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE OverloadedStrings #-}
#ifndef DEBUG
{-# LANGUAGE Safe #-}
#endif
{-# LANGUAGE Strict #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}

import Control.Arrow ((>>>))
import Control.Monad (
    MonadPlus (mplus),
    foldM_,
    forM_,
    guard,
    join,
    replicateM,
    replicateM_,
 )
import qualified Control.Monad as M
import qualified Control.Monad.ST.Strict as ST
import qualified Control.Monad.State.Strict as S
import qualified Control.Monad.Trans.Class as T

import qualified Data.Array as A
import qualified Data.Array.MArray.Safe as MA
import qualified Data.Array.IO.Safe as IOA
import qualified Data.Array.ST.Safe as STA
import qualified Data.Array.Unboxed as UA

import Data.Bits
import qualified Data.ByteString.Char8 as B8
import Data.Char
import Data.Int

import Data.Function (on)
import Data.Functor ((<&>))
import Data.Bifunctor (bimap)
import Data.Maybe (fromJust, fromMaybe, isJust)
import qualified Data.Maybe as MB

import qualified Data.IntMap as IM
import qualified Data.IntSet as IS
import qualified Data.List   as L
import Data.List (
    elemIndices,
    find,
    findIndices,
    intersect,
    isPrefixOf,
    nub,
    sort,
    sortOn,
 )
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.Ix as Ix
import qualified Data.Ratio as R

import Control.Monad.Cont (MonadIO (liftIO))
import Data.IORef (modifyIORef, newIORef, readIORef)
import GHC.IO.Handle (hDuplicateTo)
import System.IO (
    IOMode (ReadMode, WriteMode),
    openFile,
    stdin,
    stdout,
    hFlush
 )
import System.Posix.Internals (puts)
import Text.Printf (printf)
import qualified Data.Array.IO.Safe as UOA

#ifdef DEBUG
import Debug.Trace (trace, traceM, traceShowM)
debug = flip trace

tracing t x = trace (t ++ " = " ++ show x) x
debugging x t = tracing t x

tracingM t x = traceM $ t ++ " = " ++ show x

#else

debug x _ = x
trace _ x = x
tracing _ x = x
debugging x _ = x

traceM _ = pure ()
tracingM _ _ = pure ()
#endif

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

readIntB8s :: B8.ByteString -> [Int]
readIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))

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

readIntegerB8s :: B8.ByteString -> [Integer]
readIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))

modifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray arr ix f = do
    value <- MA.readArray arr ix
    MA.writeArray arr ix $ f value

putsYesNo :: Bool -> IO ()
putsYesNo value = do
    let result :: String =
            if value
                then "YES"
                else "NO"
    printf "%s\n" result

{- END OF GENERAL -}

solve :: Int -> String -> Int
solve n str = L.length groupsToInvert
    where
        bitGroups = L.group str
        groupsToInvert = L.dropWhile (\g -> L.head g == '1') . L.dropWhile (\g -> L.head g == '0') $ bitGroups

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        n <- B8.getLine <&> readIntB8
        str <- B8.getLine <&> B8.filter isAlphaNum <&> B8.unpack
        let answer = solve n str
        printf "%d\n" $ answer

import System.IO
import Control.Applicative
import Control.Monad
import Data.Char
import Data.List
import Data.Maybe
import Data.Functor
import Data.Monoid
import Data.Function (fix)
import Data.Array (Array, array, (!))
import Data.Array.ST
import Data.Array.Unboxed
import Control.Monad.ST as ST
import qualified Data.Set as Set
import qualified Data.Map.Strict as Map
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

construct :: (BS.ByteString -> Maybe (a, BS.ByteString)) -> BS.ByteString -> [a]
construct reader str
    | BS.null str = []
    | isSpace (BS8.head str) = construct reader (BS8.tail str)
    | otherwise = let Just (i, other) = reader str in i : construct reader other

getInts :: IO [Int]
getInts = construct BS8.readInt <$> BS.getLine

getIntegers :: IO [Integer]
getIntegers = construct BS8.readInteger <$> BS.getLine

printInts :: [Int] -> IO ()
printInts = putStrLn . unwords . map show

solve' xs _ _ 0 = 0
solve' (x:xs) flipCount oneCount zeroCount
    | num == 1 = 1 + solve' xs (flipCount + 1) nextZero nextOne
    | otherwise = solve' xs flipCount nextOne nextZero
    where num = (x+flipCount) `mod` 2
          nextZero = if num == 0 then zeroCount - 1 else zeroCount
          nextOne = if num == 1 then oneCount - 1 else oneCount

solve xs = solve' xs 0 oneCount zeroCount
    where oneCount = sum xs
          zeroCount = length xs - sum xs

main = do
  [t] <- getInts
  forM_ [1..t] $ \_ -> do
    _ <- getInts
    xs <- BS.getLine <&> (map digitToInt . filter (\x -> x == '0' || x == '1') . BS8.unpack)
    print $ solve xs


import Control.Arrow ((>>>))
import Data.Bool (bool)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Maybe (fromMaybe)

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf k xs =
  let (hs, ts) = splitAt k xs
   in hs : chunksOf k ts

main :: IO ()
main =
  interact $
  lines >>>
  drop 1 >>> map (words >>> map read >>> solve >>> bool "No" "Yes") >>> unlines

type I64 = Integer

solve :: [Int] -> Bool
solve [a, b, k]
  | a == 1 && b == 1 = False
  | k == 1 = a /= b && (a `mod` b == 0 || b `mod` a == 0)
  | otherwise = k <= fac a + fac b

primes :: [Int]
primes = sieve [2 .. 4 * 10 ^ 4]
  where
    sieve [] = []
    sieve (p:xs) = p : sieve (filter ((/= 0) . (`mod` p)) xs)

fac :: Int -> Int
fac n =
  (\(v, acc) -> acc + bool 1 0 (v == 1)) $
  foldl (\(v, acc) p -> f v p acc) (n, 0) primes
  where
    f v p acc
      | v `mod` p /= 0 = (v, acc)
      | otherwise = f (v `div` p) p (acc + 1)

import Control.Monad

main = do t <- read <$> getLine
          replicateM t solve

factorize :: [Int] -> Int -> Int
factorize _ 1 = 0
factorize (d:ds) n
    | d * d > n = 1
    | n `mod` d == 0 = 1 + (factorize (d:ds) (n `div` d))
    | otherwise = factorize (ds) n

primes :: [Int]
primes = 2: 3: sieve (tail primes) [5,7..]
  where
    sieve (p:ps) xs = h ++ sieve ps [x | x <- t, x `rem` p /= 0]
      where (h,~(_:t)) = span (< p*p) xs

primeFactors :: Int -> Int
primeFactors = factorize primes

solve = do arr <- map read . words <$> getLine
           let times = arr !! 2
           let a = arr !! 0
           let b = arr !! 1
           let facta = primeFactors a
           let factb = primeFactors b
           let m = if a == b
                    then 0
                    else if ((a `mod` b) == 0)|| ((b `mod` a) == 0)
                      then 1
                      else 2
           let n = facta + factb
           putStrLn $ ans m n times

ans :: Int -> Int -> Int -> String
ans m n times
  | times == 1 && m == 1 && n >= 1 = "Yes"
  | times /= 1 && m <= times && n >= times = "Yes"
  | otherwise = "No"

--prewritten code: https://github.com/antma/algo
{-# LANGUAGE BangPatterns, FlexibleContexts #-}
{-# Options_GHC -O2 #-}
import Data.ByteString.Builder
import Data.Monoid
import System.IO
import qualified Data.ByteString.Char8 as C
import Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)
import Data.Char
import Data.Array.Unboxed
import Control.Monad
import Control.Monad.ST
import Data.Array.ST
import Data.Bits
import Data.List(group,sort)

primeArray :: Int -> UArray Int Bool
primeArray n = runSTUArray $ do
  let m = max 1 (shiftR n 1)
      dhm :: Double
      dhm = sqrt $ fromIntegral $ pred n
      hm = ceiling dhm
  a <- newArray (0, m) False :: ST s (STUArray s Int Bool)
  writeArray a 0 True
  forM_ [1 .. pred hm] $ \p -> do
    l <- readArray a p
    unless l $ do
      let k = succ $ 2 * p
          loop j = when (j < m) $ do
                     writeArray a j True
                     loop (j + k)
      loop (2 * p * succ p)
  return a

isprime :: UArray Int Bool -> Int -> Bool
isprime p x = if even x then x == 2 else not (p ! shiftR x 1)

primes :: Int -> [Int]
primes n = 2 : filter ( not . (pa ! ) . (`shiftR` 1)) [3, 5 .. n]
  where
    pa = primeArray n

factors :: [Int] -> Int -> [Int]
factors p n = loop n p []
  where
    loop 1 _ r = r
    loop m l@(x:xs) r
      | x * x > m = m : r
      | mod m x == 0 = loop (div m x) l (x:r)
      | otherwise = loop m xs r

factorization :: [Int] -> Int -> [(Int, Int)]
factorization primes' n = map (\l -> (head l, length l)) $ group $ factors primes' n

divisors :: [Int] -> Int -> [Int]
divisors primes' n = sort $ loop (factorization primes' n) 1 []
  where
    loop [] !m r = m : r
    loop ((!c, !p):xs) m r = snd $ (iterate f (m, r)) !! (p + 1)
      where
        f (!m', r') = (m' * c, loop xs m' r')
ru, ri :: C.ByteString -> Int

ru = C.foldl' (\a c -> a * 10 - 48 + ord c) 0
ri s
  | C.head s == '-' = negate $ ru $ C.tail s
  | otherwise = ru s

p = primes 32000

radd (u1, v1) (u2, v2) = (u1 + u2, v1 + v2)

rng 1 = (0, 0)
rng x = (1, sum $ map snd u)
  where
    u = factorization p x

test' :: Int -> Int -> Int -> Bool
test' a b k
  | k == 1 && a /= b && ((mod a b) == 0 || (mod b a) == 0) = True
  | fst r1 <= k && k <= snd r1 = True
  | g == 1 = False
  | otherwise = (min 2 (fst r2)) <= k && k <= snd r2
  where
    g = gcd a b
    a' = div a g
    b' = div b g
    r1 = radd (rng a') (rng b')
    rg = rng g
    rg2 = radd rg rg
    r2 = radd rg2 r1
    --r = if g > 1 then radd

ans True = byteString $ C.pack "YES"
ans False = byteString $ C.pack "NO"

nl = char7 '\n'
test :: Builder -> Int -> [Int] -> Builder
test buf 0 _ = buf
test buf nt (a:b:k:xs) = test (buf <> ans (test' a b k) <> nl) (pred nt) xs

solve :: [Int] -> Builder
solve (nt:xs) = test mempty nt xs

main :: IO ()
main = hPutBuilder stdout . solve . map ri . C.words =<< C.getContents

import Control.Arrow ((>>>))
import Data.Bool (bool)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Maybe (fromMaybe)

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf k xs =
  let (hs, ts) = splitAt k xs
   in hs : chunksOf k ts

main :: IO ()
main =
  interact $
  lines >>>
  drop 1 >>> map (words >>> map read >>> solve >>> bool "No" "Yes") >>> unlines

type I64 = Integer

solve :: [Int] -> Bool
solve [a, b, k]
  | 2 <= k && k <= fac a + fac b = True
  | k > fac a + fac b = False
  | otherwise = a /= b

mx :: Int
mx = 4 * 10 ^ 4

primes :: [Int]
primes = sieve [2 .. mx]
  where
    sieve [] = []
    sieve (p:xs) = p : sieve (filter ((/= 0) . (`mod` p)) xs)

fac :: Int -> Int
fac n =
  (\(v, acc) -> acc + bool 1 0 (v == 1)) $
  foldl (\(v, acc) p -> f v p acc) (n, 0) primes
  where
    f v p acc
      | v `mod` p /= 0 = (v, acc)
      | otherwise = f (v `div` p) p (acc + 1)

import Control.Arrow ((>>>))
import Data.Bool (bool)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Maybe (fromMaybe)

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf k xs =
  let (hs, ts) = splitAt k xs
   in hs : chunksOf k ts

main :: IO ()
main =
  interact $
  lines >>>
  drop 1 >>> map (words >>> map read >>> solve >>> bool "No" "Yes") >>> unlines

type I64 = Integer

solve :: [Int] -> Bool
solve [a, b, k]
  | k == 1 = a `mod` b == 0 || b `mod` a == 0
  | otherwise = k <= fac a + fac b

mx :: Int
mx = 4 * 10 ^ 4

primes :: [Int]
primes = sieve [2 .. mx]
  where
    sieve [] = []
    sieve (p:xs) = p : sieve (filter ((/= 0) . (`mod` p)) xs)

fac :: Int -> Int
fac n =
  (\(v, acc) -> acc + bool 1 0 (v == 1)) $
  foldl (\(v, acc) p -> f v p acc) (n, 0) primes
  where
    f v p acc
      | v `mod` p /= 0 = (v, acc)
      | otherwise = f (v `div` p) p (acc + 1)

import Control.Arrow ((>>>))
import Data.Bool (bool)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Maybe (fromMaybe)

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf k xs =
  let (hs, ts) = splitAt k xs
   in hs : chunksOf k ts

main :: IO ()
main =
  interact $
  lines >>>
  drop 1 >>> map (words >>> map read >>> solve >>> bool "No" "Yes") >>> unlines

type I64 = Integer

solve :: [Int] -> Bool
solve [a, b, k]
  | a == b = k == 0
  | k == 1 = a `mod` b == 0 || b `mod` a == 0
  | otherwise = k <= fac a + fac b

mx :: Int
mx = 4 * 10 ^ 4

primes :: [Int]
primes = sieve [2 .. mx]
  where
    sieve [] = []
    sieve (p:xs) = p : sieve (filter ((/= 0) . (`mod` p)) xs)

fac :: Int -> Int
fac n = (\(v, acc) -> acc + bool 1 0 (v == 1)) $ foldl f (n, 0) primes
  where
    f (v, acc) p
      | v `mod` p /= 0 = (v, acc)
      | otherwise =
        let (v', acc') = f (v `div` p, acc) p
         in (v', acc' + 1)

import Control.Arrow ((>>>))
import Data.Bool (bool)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Maybe (fromMaybe)

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf k xs =
  let (hs, ts) = splitAt k xs
   in hs : chunksOf k ts

main :: IO ()
main =
  interact $
  lines >>>
  drop 1 >>> map (words >>> map read >>> solve >>> bool "No" "Yes") >>> unlines

type I64 = Integer

solve :: [Int] -> Bool
solve [a, b, k]
  | a == b = k == 0
  | k == 1 = a `mod` b == 0 || b `mod` a == 0
  | otherwise = k <= fac a + fac b

mx :: Int
mx = 4 * 10 ^ 4

primes :: [Int]
primes = sieve [2 .. mx]
  where
    sieve [] = []
    sieve (p:xs) = p : sieve (filter ((/= 0) . (`mod` p)) xs)

fac :: Int -> Int
fac n = snd $ foldl f (n, 0) primes
  where
    f (v, acc) p
      | v `mod` p /= 0 = (v, acc)
      | otherwise =
        let (v', acc') = f (v `div` p, acc) p
         in (v', acc' + 1)

import Control.Monad

main = do t <- read <$> getLine
          replicateM t solve

factorize :: Int -> Int -> [Int]
factorize _ 1 = []
factorize d n
    | d * d > n = [n]
    | n `mod` d == 0 = d : factorize d (n `div` d)
    | otherwise = factorize (d + 1) n

primeFactors :: Int -> [Int]
primeFactors = factorize 2

solve = do arr <- map read . words <$> getLine
           let times = arr !! 2
           let a = arr !! 0
           let b = arr !! 1
           let facta = length $ primeFactors a
           let factb = length $ primeFactors b
           putStrLn $ ans a b facta factb times

ans :: Int -> Int -> Int -> Int -> Int -> String
ans a b facta factb times
  | (a == 1) && (factb >= times) = "Yes"
  | (b == 1) && (facta >= times) = "Yes"
  | (a == 1) || (b == 1) = "No"
  | (times == 1) && (a == b) = "No"
  | (facta + factb) >= times = "Yes"
  | (times == 1) && ((a `mod` b) == 0) = "Yes"
  | (times == 1) && ((b `mod` a) == 0) = "Yes"
  | otherwise = "No"

--prewritten code: https://github.com/antma/algo
{-# LANGUAGE BangPatterns, FlexibleContexts #-}
{-# Options_GHC -O2 #-}
import Data.ByteString.Builder
import Data.Monoid
import System.IO
import qualified Data.ByteString.Char8 as C
import Data.Time (diffTimeToPicoseconds, utctDayTime, getCurrentTime)
import Data.Char
import Data.Array.Unboxed
import Control.Monad
import Control.Monad.ST
import Data.Array.ST
import Data.Bits
import Data.List(group,sort)

primeArray :: Int -> UArray Int Bool
primeArray n = runSTUArray $ do
  let m = max 1 (shiftR n 1)
      dhm :: Double
      dhm = sqrt $ fromIntegral $ pred n
      hm = ceiling dhm
  a <- newArray (0, m) False :: ST s (STUArray s Int Bool)
  writeArray a 0 True
  forM_ [1 .. pred hm] $ \p -> do
    l <- readArray a p
    unless l $ do
      let k = succ $ 2 * p
          loop j = when (j < m) $ do
                     writeArray a j True
                     loop (j + k)
      loop (2 * p * succ p)
  return a

isprime :: UArray Int Bool -> Int -> Bool
isprime p x = if even x then x == 2 else not (p ! shiftR x 1)

primes :: Int -> [Int]
primes n = 2 : filter ( not . (pa ! ) . (`shiftR` 1)) [3, 5 .. n]
  where
    pa = primeArray n

factors :: [Int] -> Int -> [Int]
factors p n = loop n p []
  where
    loop 1 _ r = r
    loop m l@(x:xs) r
      | x * x > m = m : r
      | mod m x == 0 = loop (div m x) l (x:r)
      | otherwise = loop m xs r

factorization :: [Int] -> Int -> [(Int, Int)]
factorization primes' n = map (\l -> (head l, length l)) $ group $ factors primes' n

divisors :: [Int] -> Int -> [Int]
divisors primes' n = sort $ loop (factorization primes' n) 1 []
  where
    loop [] !m r = m : r
    loop ((!c, !p):xs) m r = snd $ (iterate f (m, r)) !! (p + 1)
      where
        f (!m', r') = (m' * c, loop xs m' r')
ru, ri :: C.ByteString -> Int

ru = C.foldl' (\a c -> a * 10 - 48 + ord c) 0
ri s
  | C.head s == '-' = negate $ ru $ C.tail s
  | otherwise = ru s

p = primes 32000

radd (u1, v1) (u2, v2) = (u1 + u2, v1 + v2)

rng 1 = (0, 0)
rng x = (1, sum $ map snd u)
  where
    u = factorization p x

test' :: Int -> Int -> Int -> Bool
test' a b k
  | fst r1 <= k && k <= snd r1 = True
  | g == 1 = False
  | otherwise = fst r2 <= k && k <= snd r2
  where
    g = gcd a b
    a' = div a g
    b' = div b g
    r1 = radd (rng a') (rng b')
    rg = rng g
    rg2 = radd rg rg
    r2 = radd rg2 r1
    --r = if g > 1 then radd

ans True = byteString $ C.pack "YES"
ans False = byteString $ C.pack "NO"

nl = char7 '\n'
test :: Builder -> Int -> [Int] -> Builder
test buf 0 _ = buf
test buf nt (a:b:k:xs) = test (buf <> ans (test' a b k) <> nl) (pred nt) xs

solve :: [Int] -> Builder
solve (nt:xs) = test mempty nt xs

main :: IO ()
main = hPutBuilder stdout . solve . map ri . C.words =<< C.getContents


import qualified Data.List as L
import qualified Data.Map as M
import Data.Map (Map)
import qualified Data.Set as S
import Data.Set (Set)
import qualified Data.IntSet as IS
import Data.IntSet (IntSet)
import qualified Data.IntMap as IM
import Data.IntMap (IntMap)
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)

type Long = Int

solve :: Double -> Double
solve n = 1 / tan (pi / (2* n))

testCases :: Int -> IO ()
testCases 0 = return ()
testCases t = do
    (n:_) <- readWords
    print $ solve n
    testCases (t-1)

main :: IO ()
main = do
    (t:_) <- readWords
    testCases t

readWords :: (Read a) => IO [a]
readWords = map read . words <$> getLine

main = interact $ g . map read . tail . words

f n = 1/(tan (pi/(2*n)))

g xs = unlines (map show (map f xs))

import Data.List

solve :: Integer -> Double
solve n = 1/(tan (pi/(2* (fromIntegral n))))

main = interact $
          (intercalate "\n")
          . (map (show . solve . read))
          . (drop 1)
          . words

import Control.Monad
import Data.List

main = do
    t <- readLn :: IO Int
    replicateM_ t routine

routine = do
    n <- readLn :: IO Int
    print $ solve n

solve :: Int -> Double
solve a
    -- odd side
    | mod a 2 == 1 = 2*side
    -- even height
    | otherwise = 2*height
  where
      height =  (side ^ 2) * sin_given
      side = sin_theta / sin_given
      sin_given = sin (pi / fromIntegral a)
      sin_theta = sin (pi * (0.5*(1 - 1/fromIntegral a)))


import Control.Monad -- for replicateM_
import Data.List -- for sort

{-
 -
 - meet 0 and
 - 1. ones is empty
 -      add it to zeros.
 - 2. ones isn't empty
 -      pop ones, and add it to zeros.
 - meet 1 and
 - 1. zeros is empty
 -      add it to ones.
 - 2. zeros isn't empty
 -      pop zeros, and add it to ones.
 -}
solve :: Int -> [Bool] -> [Int] -> [Int] -> [Int]
solve now_id (False:xs) zeros [] = now_id : solve (now_id+1) xs (now_id:zeros) []
solve now_id (False:xs) zeros (o:ones) = o : solve now_id  xs (o:zeros) ones
solve now_id (True:xs) [] ones = now_id : solve (now_id+1) xs [] (now_id:ones)
solve now_id (True:xs) (z:zeros) ones = z : solve now_id  xs zeros (z:ones)
solve now_id _ _ _ = []

deal :: IO()
deal = do
    getLine
    a <- map (== '1')  <$> getLine
    let answer = solve 1 a [] []
    print $ maximum answer
    putStrLn $ unwords $ map show answer

main :: IO()
main = getLine >>= flip replicateM_ deal . read

{-# LANGUAGE BangPatterns #-}

import Data.List (unfoldr)

import qualified Data.ByteString.Lazy.Char8 as P
import qualified Data.ByteString.Lazy as R
import Data.Word (Word8)

type ByteString = P.ByteString

zeroChar :: Word8
zeroChar = R.head $ P.singleton '0'

oneChar :: Word8
oneChar = R.head $ P.singleton '1'

parseCases :: ByteString -> [ByteString]
parseCases inp = go (tail $ P.lines inp)  where
  go [] = []
  go (_nstr : s : excess) = s : go excess
  go _ = error "malformed input"

type State = (Int, Int, Int, ByteString)
step :: State -> Maybe (Int, State)
-- Idea:  pos - zeros  is the number of subsequences so far which end in zero.
--        ones - pos   is the number of subsequences so far which end in one.
-- new sequences with '0' are allocated non-negative indices,
-- new sequences with '1' are allocated     negative indices.
step (!pos, !zeros, !ones, !str) = case  R.uncons str  of
  Nothing -> Nothing
  Just (c, xs)
    | c == zeroChar -> Just (pos,   (pos+1, zeros, max ones (pos+1), xs))
    | c == oneChar  -> Just (pos-1, (pos-1, min zeros (pos-1), ones, xs))
  _ -> Nothing -- error "malformed input"

-- hopefully String is fast enough
solveCase :: ByteString -> String
solveCase inp = let
  rawAnsSeq = unfoldr step (0, 0, 0, inp)
  low = minimum rawAnsSeq
  top = maximum rawAnsSeq
  subseqCount = top + 1 - low
  as = map (1 - low +) rawAnsSeq
  in  unlines [show subseqCount, unwords (map show as)]

main :: IO ()
main = P.getContents >>= (putStr . concatMap solveCase . parseCases)

{-# LANGUAGE Safe #-}

import safe Control.Arrow ((>>>))

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

process :: [String] -> [[Int]]
process [] = []
process (_ : xs : rest) = let (k, ss) = solve xs in [k] : ss : process rest

solve :: String -> (Int, [Int])
solve = (\(_, _, ps, k) -> (k, ps)) . foldr pick ([], [], [], 0)
  where
    pick :: Char -> ([Int], [Int], [Int], Int) -> ([Int], [Int], [Int], Int)
    pick '0' (xs, [], ps, k) = ((k + 1) : xs, [], (k + 1) : ps, k + 1)
    pick '0' (xs, y : ys, ps, k) = (y : xs, ys, y : ps, k)
    pick '1' ([], ys, ps, k) = ([], (k + 1) : ys, (k + 1) : ps, k + 1)
    pick '1' (x : xs, ys, ps, k) = (xs, x : ys, x : ps, k)

{- This code was written by
Russell Emerine - linguist,
mathematician, coder,
musician, and metalhead. -}
import Control.Monad
import Data.List

main = getLine >>= flip replicateM_ test . read

test = do
  getLine
  s <- map (== '1') <$> getLine
  let a = solve 1 [] [] s
  print $ maximum a
  putStrLn $ unwords $ map show a

solve next (z : zs) os (False : s) = z : solve next zs (z : os) s
solve next [] os (False : s) = next : solve (succ next) [] (next : os) s
solve next zs (o : os) (_ : s) = o : solve next (o : zs) os s
solve next zs [] (_ : s) = next : solve (succ next) (next : zs) [] s
solve _ _ _ _ = []

import Control.Monad

rec :: Int -> [Int] -> [Int] -> [Bool] -> [Int]
rec next (z : zs) os (False : s) = z : rec next zs (z : os) s
rec next [] os (False : s) = next : rec (succ next) [] (next : os) s
rec next zs (o : os) (_ : s) = o : rec next (o : zs) os s
rec next zs [] (_ : s) = next : rec (succ next) (next : zs) [] s
rec _ _ _ _ = []

solve :: IO ()
solve = do
  getLine
  s <- map (== '1') <$> getLine
  let a = rec 1 [] [] s
  print $ maximum a
  putStrLn $ unwords $ map show a

main :: IO ()
main = do
  getLine >>= flip replicateM_ solve . read


import Control.Monad (replicateM_)
main = read <$> getLine >>= flip replicateM_ scase
scase = read <$> getLine >>=
        \n -> map read . words <$> getLine >>=
        print . minSteps n

minSteps :: Int -> [Int] -> Int
minSteps n (a:as) = foldl (\acc e -> acc + minStep a e) 0 as

minStep :: Int -> Int -> Int
minStep x y = let f = -1+div y (2*x-1) in
                if f < 0
                then 0
                else f + (if mod y (2*x-1) > 0 then 1 else 0)

import Control.Monad

toShow [] = ""
toShow (x:xs) = show x ++ " " ++ toShow xs

main :: IO ()
main = do
    ts <- getLine
    replicateM (read ts::Int) $ do
        input <- getLine
        let n = read  input ::Int
        input <- getLine
        let a = map read . words $ input ::[Int]
        let mi = minimum a

        putStrLn.show.sum .map ((`div` (2*mi-1)).subtract 1) $ a
    return ()

--
-- Michael V. Antosha
-- 2022
-- Michael.Antosha@gmail.com
--

{-# language Safe                      #-}
{-# language ImportQualifiedPost       #-}
{-# language NoMonomorphismRestriction #-}

{-# options_ghc -O3                              #-}

{-# options_ghc -Weverything                     #-}
{-# options_ghc -Werror                          #-}

{-# options_ghc -Wno-missing-import-lists        #-}
{-# options_ghc -Wno-missing-local-signatures    #-}

import Prelude               hiding (getLine)
import Control.Arrow
import Control.Monad
import Data.ByteString.Char8 qualified as B
import Data.Char
import Data.List             qualified as L

ri = readInts <$> B.getLine :: IO [Int]
  where
    readInts  = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace
    dropSpace = B.dropWhile isSpace

main :: IO ()
main = do
    [t] <- ri
    tcs <- replicateM t $ do
        [[_n],xs] <- replicateM 2 ri
        return xs
    mapM_ (putStrLn.show.solve) tcs

solve xs = sum . map cntSplit $ xs
  where
    m = minimum xs
    mx = m*2 - 1
    cntSplit x = ((x+mx-1) `div` mx) - 1

import Data.Char

second (x:y:xs) = y : second xs;
second _ = []

pieces n k
  | mod k (2*n-1) == 0 = div k (2*n-1)
  | otherwise = div k (2*n-1) +1

moves n k = pieces n k - 1
solve xs = sum $ map (moves n) ks where
  n = head xs
  ks = tail xs

main = do
  rawInput <- getContents
  let input = (second . tail) $ lines rawInput
  let ls = map ((map read) . words) input :: [[Int]]
  let output = map solve ls
  putStr (unlines $ map show output)

--
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE DatatypeContexts #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- {-# LANGUAGE Strict #-}
{-# LANGUAGE TupleSections #-}
{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}

import Control.Arrow ((>>>))
import Control.Monad (
    MonadPlus (mplus),
    foldM_,
    forM_,
    guard,
    join,
    replicateM,
    replicateM_,
 )
import qualified Control.Monad as M
import qualified Control.Monad.ST.Strict as ST
import qualified Control.Monad.State.Strict as S
import qualified Control.Monad.Trans.Class as T

import qualified Data.Array as A
import qualified Data.Array.MArray.Safe as MA
import qualified Data.Array.IO.Safe as IOA
import qualified Data.Array.ST.Safe as STA
import qualified Data.Array.Unboxed as UA

import Data.Bits
import qualified Data.ByteString.Char8 as B8
import Data.Char
import Data.Int

import Data.Function (on)
import Data.Functor ((<&>))
import Data.Bifunctor (bimap)
import Data.Maybe (fromJust, fromMaybe, isJust)
import qualified Data.Maybe as MB

import qualified Data.IntMap as IM
import qualified Data.IntSet as IS
import qualified Data.List   as L
import Data.List (
    elemIndices,
    find,
    findIndices,
    intersect,
    isPrefixOf,
    nub,
    sort,
    sortOn,
 )
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.Ix as Ix
import qualified Data.Ratio as R

import Control.Monad.Cont (MonadIO (liftIO))
import Data.IORef (modifyIORef, newIORef, readIORef)
import GHC.IO.Handle (hDuplicateTo)
import System.IO (
    IOMode (ReadMode, WriteMode),
    openFile,
    stdin,
    stdout,
    hFlush
 )
import System.Posix.Internals (puts)
import Text.Printf (printf)
import qualified Data.Array.IO.Safe as UOA

-- import Debug.Trace (trace, traceM, traceShowM)
-- debug = flip trace
--
-- tracing t x = trace (t ++ " = " ++ show x) x
-- debugging x t = tracing t x
--
-- debug x t = x
-- trace t x = x
-- tracing t x = x
-- debugging x t = x

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

readIntB8s :: B8.ByteString -> [Int]
readIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))

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

readIntegerB8s :: B8.ByteString -> [Integer]
readIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))

modifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray arr ix f = do
    value <- MA.readArray arr ix
    MA.writeArray arr ix $ f value

putsYesNo :: Bool -> IO ()
putsYesNo value = do
    let result :: String =
            if value
                then "YES"
                else "NO"
    printf "%s\n" result

{- END OF GENERAL -}

solve :: Int -> [Int] -> Int
solve n as = sum steps
    where
        minA = minimum as
        steps = map stepsFor as
        stepsFor x = (x + d - 1) `div` d - 1
            where d = 2 * minA - 1

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        n <- B8.getLine <&> readIntB8
        as <- B8.getLine <&> readIntB8s
        let answer = solve n as
        printf "%d\n" answer

import Control.Monad

toShow [] = ""
toShow (x:xs) = show x ++ " " ++ toShow xs

main :: IO ()
main = do
    ts <- getLine
    replicateM (read ts::Int) $ do
        input <- getLine
        let n = read  input ::Int
        input <- getLine
        let a = map read . words $ input ::[Int]
        let mi = minimum a

        putStrLn.show.sum .map (if mi==1 then subtract 1 else  (`div` (2*mi-1))) $ a
    return ()


main :: IO ()
main = do
	n <- getLine
	let number = read n :: Int
	solve number number
	return ()

solve :: Int -> Int -> IO ()
solve number 0 = return ()
solve number current = 	do
				line <- getLine
				if length line < 3
					then do
						putStrLn  $ [(last line)]
						solve number (current - 1)
				    else do
						putStrLn  $ [(foldr min '9' line)]
						solve number (current - 1)

module Main (main)
where

import Data.List
import Data.Char

main :: IO ()
main = intercalate "\n" <$> map show <$> map solve <$> map readInts <$> (read <$> getLine >>= readNLines) >>= putStrLn

readNLines :: Int -> IO [String]
readNLines n = sequence $ replicate n getLine

readInts :: String -> [Int]
readInts s = foldr (\x acc -> (ord x - 48):acc) [] s

-- [Int] at least two digits
solve :: [Int] -> Int
solve [a, b] = b
solve xs = minimum xs

import Control.Monad
import Data.Maybe
import Data.Char
import qualified Data.ByteString.Char8 as C
import Data.ByteString.Builder
import System.IO

parseInt :: C.ByteString -> Int
parseInt = fst . fromJust . C.readInt

getInts :: IO [Int]
getInts = map parseInt . C.words <$> C.getLine

main :: IO ()
main = do
  [caseNum] <- getInts
  output <- fmap mconcat $ forM [1..caseNum] $ \_ -> do
    s <- filter (not . isSpace) . C.unpack <$> C.getLine
    return $ char7 (if length s == 2 then s !! 1 else minimum s) <> char7 '\n'
  hPutBuilder stdout output

-- https://codeforces.com/contest/1679/problem/D
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE DatatypeContexts #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE Strict #-}
{-# LANGUAGE TupleSections #-}

import Control.Arrow ((>>>))
import Control.Monad (
    MonadPlus (mplus),
    foldM_,
    forM_,
    guard,
    join,
    replicateM,
    replicateM_,
 )
import qualified Control.Monad.ST.Strict as ST
import qualified Control.Monad.State.Strict as S

import qualified Data.Array as A
import qualified Data.Array.MArray.Safe as MA
import qualified Data.Array.ST.Safe as STA
import qualified Data.Array.Unboxed as UA

import Data.Bits
import qualified Data.ByteString.Char8 as B8
import Data.Char
import Data.Int

import Data.Function (on)
import Data.Functor ((<&>))
import Data.Bifunctor (bimap)
import Data.Maybe (fromJust, fromMaybe, isJust)

import qualified Data.IntMap as IM
import qualified Data.IntSet as IS
import qualified Data.List   as L
import Data.List (
    elemIndices,
    find,
    findIndices,
    intersect,
    isPrefixOf,
    nub,
    sort,
    sortOn,
 )
import qualified Data.Map as M
import qualified Data.Set as S

import Control.Monad.Cont (MonadIO (liftIO))
import Data.IORef (modifyIORef, newIORef, readIORef)
import GHC.IO.Handle (hDuplicateTo)
import System.IO (
    IOMode (ReadMode, WriteMode),
    openFile,
    stdin,
    stdout,
 )
import System.Posix.Internals (puts)
import Text.Printf (printf)

-- import Debug.Trace (trace, traceM, traceShowM)
-- debug = flip trace

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

readIntB8s :: B8.ByteString -> [Int]
readIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))

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

readIntegerB8s :: B8.ByteString -> [Integer]
readIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))

modifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray arr ix f = do
    value <- MA.readArray arr ix
    MA.writeArray arr ix $ f value

putsYesNo :: Bool -> IO ()
putsYesNo value = do
    let result :: String =
            if value
                then "Yes"
                else "No"
    printf "%s\n" result

{- END OF GENERAL -}

solve :: Int -> Int
solve n = solve' digits
    where
        digits = map (\c -> ord c - ord '0') $ show n
        solve' = \case
            [a] -> a
            [a, b] -> b
            ds -> foldr1 min ds

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        a <- B8.getLine <&> readIntB8
        let answer = solve a
        printf "%d\n" answer

import Data.Char

solve :: String -> Char
solve number = if length number == 2
               then number !! 1
               else chr (minimum (map ord number))

mainLoop 0 = return ()
mainLoop t = do number <- getLine
                putStrLn [solve number]
                mainLoop (t - 1)

main = do t <- (readLn :: IO Int)
          mainLoop t

import Control.Monad
import Data.Maybe
import qualified Data.ByteString.Char8 as C
import Data.ByteString.Builder
import System.IO

parseInt :: C.ByteString -> Int
parseInt = fst . fromJust . C.readInt

getInts :: IO [Int]
getInts = map parseInt . C.words <$> C.getLine

main :: IO ()
main = do
  [caseNum] <- getInts
  output <- fmap mconcat $ forM [1..caseNum] $ \_ -> do
    s <- C.unpack <$> C.getLine
    return $ char7 (if length s == 2 then s !! 1 else minimum s) <> char7 '\n'
  hPutBuilder stdout output