main = interact $ unlines . map (show . joseph . map read . words) . init . lines

joseph [n,m] = joseph' [1..n]
 where
  joseph' [x] = x
  joseph' xs = joseph' (filter (/= x) (take (length xs) xs'))
   where (x:xs') = (drop (m-1) (cycle xs))