Problems > Count the Derangements

Count the Derangements

Difficulty: 1600 3000 ms 128 MB

math combinatorics

A derangement is a permutation with no fixed point (no element stays in its own position). Count the derangements of N items modulo 109+7.

Input: one integer N.

Output: DN mod 109+7.

Constraints:

  • 0 ≤ N ≤ 106

Sample Tests

Input 1
3
Output 1
2
Input 2
1
Output 2
0

Read the Editorial

Discussion (opens after you solve — no spoilers before)

No comments yet.

Submit Your Solution

Log in or create a free account to run and submit code.