All problems

Problem 553

Count Derangements

Medium · 20 pts · Math, Dynamic Programming, Combinatorics

Problem

A derangement of N items is an arrangement in which no item stays in its original position. Count the derangements of N items, modulo 1000000007. They follow the recurrence D(n) = (n - 1) × (D(n - 1) + D(n - 2)), with D(0) = 1 (the empty arrangement) and D(1) = 0 (a single item cannot move). Compute it iteratively, taking the remainder at every step. Keep the counts in a 64-bit integer type (long long in C++, long in Java) and take the remainder after every addition and multiplication: adding or multiplying two remainders can be larger than a 32-bit int can hold (Python needs nothing special).

Input

A single integer N.

Output

Print the number of derangements of N items modulo 1000000007.

Constraints

0 <= N <= 1000000

Example input

3

Example output

2

Explanation

For N = 3 with items 1 2 3, the derangements are 2 3 1 and 3 1 2. Every other order leaves at least one item in place, so the answer is 2.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Count Square-Free Numbers Next: Binomial Coefficient Modulo a Small Prime