F-35's blog

By F-35, history, 8 months ago, In English,

Hello coders! let's suppose we have three numbers n,k,mod=1e9+7 where n,k<=1e9 how to calculate nCk %mod! any hint please! Thanks^__^

 
 
 
 
  • Vote: I like it
  • 0
  • Vote: I do not like it

»
8 months ago, # |
Rev. 2   Vote: I like it -18 Vote: I do not like it

You can calculate N! in O(log(N)) using Matrix Multiplication, then calculate N! / [ K! * (N &mdash; K)! ] % mod How ? (only when mod is prime)

(A / B) % mod = A * Pow(B, mod &mdash; 2) % mod
  • »
    »
    8 months ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    thanks but how to calculate N! in log(n)?

  • »
    »
    8 months ago, # ^ |
    Rev. 2   Vote: I like it +16 Vote: I do not like it

    If you can calculate n! in O(log(n)) then you have solved prime checking in O(log3(n)) or something. See this.

    • »
      »
      »
      8 months ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      so we can calculate n! % mod only using linear solution?

      • »
        »
        »
        »
        8 months ago, # ^ |
          Vote: I like it +35 Vote: I do not like it

        See this. The main idea is sqrt decomposition and Lagrange interpolation. The complexity is .

        • »
          »
          »
          »
          »
          8 months ago, # ^ |
            Vote: I like it 0 Vote: I do not like it

          Thank you so much :)

»
8 months ago, # |
  Vote: I like it +23 Vote: I do not like it

Another approach is precalculate 106!, (2·106)!, ..., 109! locally and paste it in your code. Then you can easily calculate every factorial using 106 multiplications.