The alternating factorial is an alternating sum of decreasing factorials. For example, we could calculate the alternating factorial of 4 as follows:
- First, calculate the factorials from 4 down to 1:
$$ 4!\quad3!\quad2!\quad1!\quad = \\ 4\cdot3\cdot2\cdot1\qquad3\cdot2\cdot1\qquad2\cdot1\qquad1\quad= \\ 24\quad6\quad2\quad1 $$
- Next, insert alternating signs between the products, always starting with \$\;-\$.
$$ 24-6+2-1 = \\ 19 $$
So 19 is the alternating factorial of 4. Mathematically, the alternating factorial is defined as $$ \large\operatorname{af}(n) = \sum_{i=1}^n(-1)^{n-i}i! $$
For example, $$ \operatorname{af}(4)=(-1)^3\times1!+(-1)^2\times2!+(-1)^1\times3!+(-1)^0\times4!=19 $$ The alternating factorial can also be calculated by the recurrence relation $$ \operatorname{af}(n) = \begin{cases} 0, & \text{if $\;n=0$} \\ n!-\operatorname{af}(n-1), & \text{if $\;n>0$} \end{cases} $$ The sequence of alternating factorials is OEIS A005165.
Task
Given a non-negative integer as input, output its alternating factorial. You don't need to worry about values exceeding your language's integer limit. This is code-golf, so the code with the fewest bytes (in each language) wins.
Test cases
n af(n)
0 0
1 1
2 1
3 5
4 19
5 101
6 619
7 4421
8 35899
9 326981