Help needed in CSEQ - April15 Long Challenge

I was trying to understand this solution. But I’m not able to get what does the following code do?

long long factorial(int n)
{
	long long res = 1; 
	while (n > 0)
	{
		for (int i = 2, m = n % MOD; i <= m; i++)
			res = (res * i) % MOD;
		if ((n /= MOD) % 2 > 0) 
			res = MOD - res;
	}
	return res;
}

Can someone please help?