Problem:
Score : 100 points

Problem Statement

In this problem, you should process T testcases.

For each testcase, you are given four integers N, M, A, B.

Calculate \sum_{i = 0}^{N - 1} floor((A \times i + B) / M).

Constraints

1 \leq T \leq 100,000

1 \leq N, M \leq 10^9

0 \leq A, B < M

Input

Input is given from Standard Input in the following format:

T
N_0 M_0 A_0 B_0
N_1 M_1 A_1 B_1
:
N_{T - 1} M_{T - 1} A_{T - 1} B_{T - 1}

Output

Print the answer for each testcase.

Sample Input 1

5
4 10 6 3
6 5 4 3
1 1 0 0
31415 92653 58979 32384
1000000000 1000000000 999999999 999999999

Sample Output 1

3
13
0
314095480
499999999500000000

Solution in Haskell (GHC 8.8.3) (judge verdict: Wrong Answer)

import qualified Control.Arrow         as Arrow
import qualified Data.ByteString.Char8 as BSC8
import qualified Data.Char             as Char
import qualified Data.Vector           as V
import qualified Data.Vector.Unboxed   as VU

type Parser a = BSC8.ByteString -> Maybe (a, BSC8.ByteString)
parseInt :: Parser Int
parseInt = fmap (Arrow.second BSC8.tail) . BSC8.readInt
parse1 :: IO Int
parse1 = readLn
parseNM :: Int -> Int -> IO (V.Vector (VU.Vector Int))
parseNM n m = V.replicateM n $ VU.unfoldrN m parseInt <$> BSC8.getLine

main :: IO ()
main = do
  t    <- parse1
  nmab <- parseNM t 4
  putStr . unlines . map show . V.toList $ V.map sumOfFloorLinear nmab

sumOfFloorLinear :: VU.Vector Int -> Int
sumOfFloorLinear nmab = floorSum n m a b
  where
    n = nmab VU.! 0
    m = nmab VU.! 1
    a = nmab VU.! 2
    b = nmab VU.! 3

floorSum :: Int -> Int -> Int -> Int -> Int
floorSum n m a b
  | a >= m && b >= m = if y1 == 0 then ret1 else ret1' + floorSum y1 a1 m ((a1 - x1 `mod` a1) `mod` a1)
  | a >= m && b <  m = if y2 == 0 then ret2 else ret2' + floorSum y2 a2 m ((a2 - x2 `mod` a2) `mod` a2)
  | a <  m && b >= m = if y3 == 0 then ret3 else ret3' + floorSum y3 a3 m ((a3 - x3 `mod` a3) `mod` a3)
  | otherwise        = if y4 == 0 then ret4 else ret4' + floorSum y4 a4 m ((a4 - x4 `mod` a4) `mod` a4)
  where
    ret1  = ((n - 1) * n * (a `div` m) `div` 2) + n * (b `div` m)
    a1    = a `mod` m
    b1    = b `mod` m
    y1    = (a1 * n + b1) `div` m
    x1    = y1 * m - b1
    ret1' = ret1 + (n - (x1 + a1 - 1)) * y1

    ret2  = (n - 1) * n * (a `div` m) `div` 2
    a2    = a `mod` m
    b2    = b
    y2    = (a2 * n + b2) `div` m
    x2    = y2 * m - b2
    ret2' = ret2 + (n - (x2 + a2 - 1)) * y2

    ret3  = n * (b `div` m)
    a3    = a
    b3    = b `mod` m
    y3    = (a3 * n + b3) `div` m
    x3    = y3 * m - b3
    ret3' = ret3 + (n - (x3 + a3 - 1)) * y3

    ret4  = 0
    a4    = a
    b4    = b
    y4    = (a4 * n + b4) `div` m
    x4    = y4 * m - b4
    ret4' = ret4 + (n - (x4 + a4 - 1)) * y4