# Mathematics Tricks For Competitive Programming In Python 3

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 n
_{Cr}and n_{Pr}

#### Modular Exponentiation

Given 3 numbers A, B and Mod.Calculate (A^{B})%Mod. **Examples:**

Input :A = 4, B = 3 Mod = 11Output :9Explanation:(4^{3})%11 = (64)%11 = 9Input :A = 3, B = 3 Mod = 5Output :2Explanation:(3^{3})%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 = 11Output :3Explanation:(4*3)%11 = (12)%11 = 1Input :A = 3, Mod = 5Output :2Explanation:(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 = 3Output :Ncr = 120Input :N = 10, r = 3Output :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**