Boring Factorials in python

2024/10/9 12:31:18

I am trying to understand and solve the following problem :

Sameer and Arpit want to overcome their fear of Maths and so they have been recently practicing Maths problems a lot. Aman, their friendhas been helping them out. But as it goes, Sameer and Arpit have gotbored of problems involving factorials. Reason being, the factorialsare too easy to calculate in problems as they only require the residuemodulo some prime and that is easy to calculate in linear time. So tomake things interesting for them, Aman - The Mathemagician, gives theman interesting task. He gives them a prime number P and an integer Nclose to P, and asks them to find N! modulo P. He asks T such queries.

Input :

First line contains an integer T, the number of queries asked.

Next T lines contains T queries of the form “N P”. (quotes forclarity)

Output:

Output exactly T lines, containing N! modulo P.

Example
Input:
32 55 1121 71Output:
2106Constraints:1 <= T <= 10001 < P <= 2*10^91 <= N <= 2*10^9Abs(N-P) <= 1000

now to this I wrote a solution :

def factorial(c):
n1=1
n2=2
num=1
while num!=c:n1=(n1)*(n2)n2+=1num+=1
return n1for i in range(int(raw_input())):n,p=map(int,raw_input().split())print factorial(n)%p

but as you can see this is inefficient solution so I started searching for a better solution than I came to know that this can be solved using wilson's and fermet's theorem.But I am unable to understand what the author is trying to say He says:

**In number theory, Wilson's theorem states that a natural number n > 1 is a prime number if and only if

enter image description here

Now from this we can write:

(p-1)!   ≡  -1 (mod p)1*2*3*.........*(n-1)*(n)*..............*(p-1)  ≡   -1 (mod p)n!*(n+1)*...........*(p-1)   ≡   -1 (mod p)n!  ≡    -1*[(n+1)*...............(p-2)*(p-1)]^-1 (mod p)let a=[(n+1)*...............(p-2)*(p-1)]son!≡-1*a^-1(mod p)From Fermat's Theorem:a^(p-1) ≡ 1(mod p)multiply both side by a^-1a^(p-2)  ≡ a^-1(mod p)now simply we have to find a^(p-2) mod p

**

so I implemented this:

def factorial1(n,p):            # to calculate  a=[(n+1)*...............(p-2)*(p-1)]
n0=n+1
n1=n0+1
while n1<=(p-1):n0=n1*n0n1+=1
return n0
# print nf(2,5)for i in range(10):n,p=map(int,raw_input().split())if n>p:print 0elif n==p-1:print p-1else:print (factorial1(n,p)**(p-2))%p   #a^(p-2) mod p

But from the output which I am getting I think I misunderstood what he wrote .Can someone tell me what is he telling me to calculate and how do I write the code for what he is saying.

Answer

This is not a straight-forward application of the Wilson's theorem. Along with it use the following facts:

  • if n >= p then n! = 0 (mod p)
  • if n < p then n! = (p-1)!/[(n+1)(n+2)..(p-1)]. Now use the fact that (p-1)! = -1 (mod p). All that is left for you to find is the modular multiplicative inverse (using extended Euclidean algorithm for example) of the numbers n+1, n+2, ... , p-1 which number is at most 1000 from the fact that abs(n-p) <= 1000. Multiply (p-1)! = -1 (mod p) with all modular multiplicative inverse of the numbers n+1, n+2, ... , p-1 and you get the answer. (as John Coleman pointed out you could also do a inverse of the the product and not product of the inverse as an optimization)

In your case n=2, p=5 (just to see how it works)

n! = 2! = 4!/(3*4) = (-1)*2*4 = 2 (mod 5)# 2 is modular inverse of 3 since 2*3 = 1 (mod 5)
# 4 is modular inverse of 4 since 4*4 = 1 (mod 5)
https://en.xdnf.cn/q/70020.html

Related Q&A

The flask host adress in docker run

I want to run a flask application in Docker, with the flask simple http server. (Not gunicorn)I got a host setting problem. In the flask app.py, it should be work as the official tutorial, but it doesn…

Extracting text from pdf using Python and Pypdf2

I want to extract text from pdf file using Python and PYPDF package. This is my pdf fie and this is my code:import PyPDF2 opened_pdf = PyPDF2.PdfFileReader(test.pdf, rb)p=opened_pdf.getPage(0)p_text= p…

Is it possible to change turtles pen stroke?

I need to draw a bar graph using Pythons turtle graphics and I figured it would be easier to simply make the pen a thick square so I could draw the bars like that and not have to worry about making doz…

How to make a local Pypi mirror without internet access and with search available?

Im trying to make a complete local Pypi repository mirror with pip search feature on a server I can only connect an external hard drive to. To be clear, I dont want a simple caching system, the server …

Turn an application or script into a shell command

When I want to run my python applications from commandline (under ubuntu) I have to be in the directory where is the source code app.py and run the application with commandpython app.pyHow can I make i…

pytest - monkeypatch keyword argument default

Id like to test the default behavior of a function. I have the following:# app/foo.py DEFAULT_VALUE = hellodef bar(text=DEFAULT_VALUE):print(text)# test/test_app.py import appdef test_app(monkeypatch):…

How remove a program installed with distutils?

I have installed a python application with this setup.py:#!/usr/bin/env pythonfrom distutils.core import setup from libyouandme import APP_NAME, APP_DESCRIPTION, APP_VERSION, APP_AUTHORS, APP_HOMEPAGE,…

How to check which line of a Python script is being executed?

Ive got a Python script which is running on a Linux server for hours, crunching some numbers for me. Id like to check its progress, so Id like to see what line is being executed right now. If that was …

input to C++ executable python subprocess

I have a C++ executable which has the following lines of code in it /* Do some calculations */ . . for (int i=0; i<someNumber; i++){int inputData;std::cin >> inputData;std::cout<<"T…

pandas extrapolation of polynomial

Interpolating is easy in pandas using df.interpolate() is there a method in pandas that with the same elegance do something like extrapolate. I know my extrapolation is fitted to a second degree polyno…