Related Articles

Mathematics Tricks For Competitive Programming In Python 3

• Difficulty Level : Basic
• Last Updated : 08 Jul, 2021

Here are some of the exciting features that Python 3.8 provides for programmers in competitive programming. These new features are related to some math functions and algorithms that are frequently used by competitive programmers. The implementation of these features has the time complexity which is the same in case of a program when implemented from scratch.
We will discuss

• Modular Exponentiation
• Multiplicative Modulo Inverse
• Calculating nCr and nPr

Modular Exponentiation

Given 3 numbers A, B and Mod.Calculate (AB)%Mod.
Examples:

```Input : A = 4, B = 3 Mod = 11
Output : 9
Explanation: (43)%11 = (64)%11 = 9

Input : A = 3, B = 3 Mod = 5
Output : 2
Explanation: (33)%5 = (27)%5 = 2```

The traditional Implementation of Modular Exponentiation is discussed here
Below is the discussed Python3.8 solution

PYTHON

 `A ``=` `4``B ``=` `3``Mod ``=` `11` `# Power function can take 3``# parameters and can compute``# (A ^ B)% Mod``print``(f``'The power is {pow(A, B, Mod)}'``)`

Output:

`The power is 9`

Modular Multiplicative Inverse

Given two integers A and Mod, Calculate Modular multiplicative inverse of A under modulo Mod.
The modular multiplicative inverse is an integer B such that

`(A.B)%Mod = 1 where gcd(A, Mod) should be equal to 1`

Examples:

```Input : A = 4, Mod = 11
Output : 3
Explanation: (4*3)%11 = (12)%11 = 1

Input : A = 3, Mod = 5
Output : 2
Explanation: (3*2)%5 = (6)%5 = 1```

The traditional Implementation of Modular Multiplicative Inverse is discussed here
Below is the discussed Python3.8 solution

Python

 `A ``=` `4``Mod ``=` `11` `# Power function can take 3 parameters``# and can compute (A^-1)% Mod``print``(f'The Modular Multiplicative Inverse \``of A under Mod ``is` `{``pow``(A, ``-``1``, Mod)}')`

Output:

`The Modular Multiplicative Inverse of A under Mod is 3`

Calculating Ncr and Npr

Given the value of N and r. Calculate the Ncr (Combinations of N things taken r at a time) and Npr(Permutations of N things taken r at a time).
Examples:

```Input : N = 10, r = 3
Output : Ncr = 120

Input : N = 10, r = 3
Output : Npr = 720```

The traditional implementations of Ncr and Npr are discussed here and here
Below is the discussed Python3.8 solution.

PYTHON

 `import` `math``N ``=` `10``r ``=` `3` `print``(f``"Ncr = {math.comb(N, r)}"``)``print``(f``"Npr = {math.perm(N, r)}"``)`

Output:

```Ncr = 120
Npr = 720```

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up