main :: IO () main = interact $ (\(base:xs) -> concatMap (allGrays (read base) . read) xs) . lines allGrays :: Int -> Int -> String allGrays base x = unlines $ map eachGray [0..x-1] where eachGray = concatMap show . toGray base . toBase base (logB base x) logB :: Int -> Int -> Int logB base = ceiling . logBase (fromIntegral base) . fromIntegral toBase :: Int -> Int -> Int -> [Int] toBase base = toBase' where toBase' :: Int -> Int -> [Int] toBase' len 0 = replicate len 0 toBase' len x = toBase' (len - 1) (x `div` base) ++ [x `mod` base] toGray :: Int -> [Int] -> [Int] toGray base = toGray' 0 where toGray' :: Int -> [Int] -> [Int] toGray' _ [] = [] toGray' shift (x:xs) = (x + shift) `mod` base : toGray' (shift + base - x) xs