Factorial inverse metaline push (Consolidation + optimization)

Source: Internet
Author: User

Sometimes N is often used when calculating the number of combinations! If n is less than or equal to 1e5, it can be preprocessed by O (N). Of course, the MOD is usually 1e9 + 7.

The code is not hard to write:

FAC [0] = 1;
For (INT I = 1; I <= N; I ++) FAC [I] = (FAC [I-1] * I) % MOD;
Inv [N] = pow_mod (FAC [N], mod-2); // FAC [N] ^ {mod-2}
For (INT I = n-1; I> = 0; I --) inv [I] = inv [I + 1] * (I + 1) % MOD;

Then directly return FAC [N] * inv [m] % mod * inv [N-M] % MOD; // calculate C (n, m), be sure not to overflow

If mod is smaller than N, pay attention to it, because if inv [I + 1] = 0, it will lead to 0 in the front, and although it has not been studied in depth, however, in this case, the effect is not very good,

Therefore, this preprocessing is only used on MOD 1e9 + 7 or 1e9 + 9. (Just me)

Factorial inverse metaline push (Consolidation + optimization)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.