N! MoD P's method of finding

Source: Internet
Author: User

We assume that P is prime, n! =a*pe, we need to solve a mod p and E.

E is n! The number of times that divisible p can be iterated, so use the following formula:

N/p+n/p2+n/p3 ...

We only need to calculate the pt≤n T, so the complexity is O (LOGPN)

Next calculate a mod p.

First calculate the n! The product of an item that cannot be divisible by P in the factor.

As a simple example, it is not difficult to find that items that cannot be divisible by P are periodically under mod p.

Therefore, the n! can be The sum of the items in the factor that cannot be divisible by P is as follows:

(p-1)! (n/p) * (n mod p)!.

According to Wilson's theorem, we have (p-1)! ≡-1. So this time we just need to ask for n/p's parity and (n mod p)! You can do it.

//Wilson theorem and proof see: http://www.cnblogs.com/wls001/p/5160288.html

Then we only have to preprocess the range of 0<=n<p n! MoD P's table will be able to calculate the answer in O (logp N) time. If not preprocessed, then the complexity is O (P logp N).

N! MoD P's method of finding

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.