I was asked the following question in an interview:
How to solve this: ((3000000!)/(30!)^100000)%(any prime no.)
I coded the C program for same using brute force, but I am sure that he was not expecting this. Any suggestions for the solutions?
I was asked the following question in an interview:
How to solve this: ((3000000!)/(30!)^100000)%(any prime no.)
I coded the C program for same using brute force, but I am sure that he was not expecting this. Any suggestions for the solutions?
3000000! = 1*2*3*4*5*..*8*...*16*...*24*...*32*...40*...*64*...*3000000
Can we count the number of 2s in the result? Yes, each power of 2 contributes one 2 to each of its multiples. So the total number of 2s in the factorization of n! is n/2 + n/4 + n/8 + n/16 + n/32 + ...
where /
is integer division and terms are summed up while they are greater than 0:
fnf n f = -- number of `f` factors in `n!`
sum . takeWhile (>0) . tail . iterate (`div` f) $ n
(writing the pseudocode in Haskell). when f*f < n
, there will be more than one entry to sum up. For bigger f
s, there will be only one entry to sum, viz. n `div` f
.
So the factorization of n!
is found as
factfact n = -- factorization of n! as [ (p,k) ... ] for n! = PROD p_i^k_i
let
(ps,qs) = span (\p-> p*p <= n) primes -- (before, after)
in
[(f, fnf n f) | f <- ps] ++
[(f, n `div` f) | f <- takeWhile (<= n) qs]
Now, factorization of 30! has 10 factors:
> factfact 30
[(2,26),(3,14),(5,7),(7,4),(11,2),(13,2),(17,1),(19,1),(23,1),(29,1)]
The 100000th power of it just has each of its factor coefficients multiplied by 100000. When we take the factorization of 3000000!, its first few terms out of 216816 total, are:
> factfact 3000000
[(2,2999990),(3,1499993),(5,749998),(7,499996),(11,299996),(13,249998),
(17,187497),(19,166665),(23,136361),(29,107142),(31,99998), ...
so after the division when we subtract the second from the first none are lacking nor cancelled out completely:
[(2,399990),(3,99993),(5,49998),(7,99996),(11,99996),(13,49998),
(17,87497),(19,66665),(23,36361),(29,7142),(31,99998), ...
So for any prime less than 3000000 the remainder is 0. What if it is bigger, p > 3000000
? Then, modular exponentiation mod p and multiplication mod p for this factorization, that we found above, must be used. There are plenty of answers about those, on SO.
Of course in the production code (for a non-lazy programming language) we wouldn't build the intermediate factorization list, but instead just process each prime below 3000000, one by one (there's no need for that with a lazy language).