import Data.List (foldl', scanl) md :: Int md = 10^9 + 7 -- sometimes ambigious infixl 6 +++ (+++) :: Int -> Int -> Int (+++) a b = (a + b) `mod` md infixl 7 *** (***) :: Int -> Int -> Int (***) a b = a * b `mod` md infixr 8 ^^^ (^^^) :: Int -> Int -> Int (^^^) a b | b == 0 = 1 | odd b = a *** a ^^^ (b - 1) | otherwise = (a *** a) ^^^ (b `div` 2) modinv :: Int -> Int modinv a = a ^^^ (md - 2) infixl 7 /// (///) :: Int -> Int -> Int (///) a b = a *** modinv b prodmod :: [Int] -> Int prodmod = foldl' (***) 1 -- p/(x-0) p/(x-1) -- vvvvvvvvvvvvvvvvvvvv vvvvvvvvvvvvvvvvvvvv -- (x-1)(x-2)...(x-n+1) (x-0) (x-2)(x-3)...(x-n+1) -- --------------------- a[0] + ... ---------------------------- a[1] + ... -- (0-1)(0-2)...(0-n+1) (1-0) (1-2)(1-3)...(1-n+1) -- ^^^^^ ^^^^^^^^^^^^^^^^^^^^ -- [L] [R] lagrange :: [Int] -> Int -> Int lagrange a x | x < n = a !! x | otherwise = let (sm, _, _, _) = foldl' f (0, 0, 1, q) a in sm where n = length a p = prodmod [(x - i) | i <- [0..n-1]] q = prodmod [-i | i <- [1..n-1]] f :: (Int, Int, Int, Int) -> Int -> (Int, Int, Int, Int) f (sm, k, l, r) ak = (nextSm, k + 1, nextL, nextR) where nextSm = sm +++ ak *** p /// (l *** r *** (x-k)) nextL = l *** (k + 1) nextR = r /// negate (n - 1 - k) computeSmall :: Int -> [Int] computeSmall k = scanl f 0 [1..k + 1] where f s x = s +++ (x ^^^ k) solve :: Int -> Int -> Int solve n k = lagrange (computeSmall k) (n `mod` md) main = do [n, k] <- map read . words <$> getLine :: IO [Int] print $ solve n k