For 30:
(!4−4)×(4!4)
=(9−4)×(244)=5×6=30
For 31:
44−4−!4
=44−4−9=31
Note that:
!n is the subfactorial of n.
For a non-negative-integer n this is the number of derangements of n
(the number of ways to arrange n items such that no item is at its naturally ordered position)
This is
n!∑ni=0(−1)ii!
As such
!4=4!∑4i=0(−1)ii!=24×((−1)00!+(−1)11!+(−1)22!+(−1)33!+(−1)44!)
=24×(11+−11+12+−16+124)
=(24−24+12−4+1)
=9
Or, using ABCD the 9 derangements are:
1. BADC
2. BCDA
3. BDAC
4. CADB
5. CDAB
6. CDBA
7. DABC
8. DCAB
9. DCBA
But not any of the other 15 permutations:
ABCD . ACDB . BACD . CABD . DACB
ABDC . ADBC . BCAD . CBAD . DBAC
ACBD . ADCB . BDCA . CBDA . DBCA