How to compute $f(n)\%M$ , where $f(n)=1^n*2^{n-1}*3^{n-2}*4^{n-3}*\dots*n^1$ and $M=10^9+7$

78 Views Asked by At

I am new to modular and computer programming for it, today in one of the contest I have got this problem tried by going with the brute force method but not able to solve in the required time limit.

This is what I was trying to do, $$f(3) = 1\cdot1\cdot1\cdot2\cdot2\cdot3$$ $$f(4) = 1\cdot1\cdot1\cdot1\cdot2\cdot2\cdot2\cdot3\cdot3\cdot4$$ $$f(5) = 1\cdot1\cdot1\cdot1\cdot1\cdot2\cdot2\cdot2\cdot2\cdot3\cdot3\cdot3\cdot4\cdot4\cdot5$$

But I was unable to solve as $n$ can take value upto $10^9$.

So I want to know that if some better algorithm/ method exist for solving this type of problem in mathematics.

Thank You, your help would be appreciated.

1

There are 1 best solutions below

0
On BEST ANSWER

Read some of the submissions on codechef and you will find some algorithms. The simplest direct approach is to use the facts that:

$$(a\times b)\%c=[(a\%c)\times(b\%c)]\%c$$

$$(a^b)\%c=\begin{cases}1,&b=0\\ [(a^2)\%c]^{b/2}\%c,&2~|~b\\ [a\times(a^b)]\%c,&\text{else}\end{cases}$$

Further optimizations can be done e.g. the result is almost always zero as long as $n$ is greater than or equal to the largest prime factor of $M$, but for most purposes, the above and a suitable fast language (namely C++ as you can see by the submissions) can get the job done.

Quick and dirty python program.

The intended approach was most likely to use the fact that

$$f(n)=\prod_{k=1}^nk!$$

as pointed out by Yves Daoust, from which one can do this with a simple for loop. python code.