Assuming that int is a fixed-width signed (using 2's complement) integer type with width w, the result is 1 if w=1, 2 if w=2, or 0 if w>2.
Proof: Note that under 2's complement, w-bit integers can be represented using arithmetic modulo 2w, i.e. all congruent numbers have the same 2's complement representation. This both proves that the recursion will eventually reach the base case where n is congruent to 0, and allows us to compute the result of factorial(-1). For w=1, -1 is congruent to 1, so we compute 1! modulo 1, which is 1. For w=2, -1 is congruent to 3, so we compute 3! modulo 4, which is 2. For w>2, we need to compute (2w-1)! modulo 2w. Notice that 2w-2 and 2w-1 are both less than 2w-1, and therefore 2w-2×2w-1=22w-3 divides the factorial. Finally, since w≥3, we have 2w-3≥w, and therefore 2w divides 22w-3, which divides the factorial. Therefore the factorial is congruent to 0 modulo 2w. ∎
View all comments
Show parent comment
1
u/froggie-style-meme Mar 24 '20
Oh
Oh god no. Good luck dealing with when the user inputs 0.