07.07.2023 Views

Implementing-cryptography-using-python

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 4 ■ Cryptographic Math and Frequency Analysis 113

Φ(2) = 1

gcd (1, 2) is 1, but gcd (2, 2) is 2

Φ (3) = 2

gcd (1, 3) is 1 and gcd (2, 3) is 1

Φ (4) = 2

gcd (1, 4) is 1 and gcd (3, 4) is 1

Φ (5) = 4

gcd (1, 5) is 1, gcd (2, 5) is 1,

gcd (3, 5) is 1, and gcd (4, 5) is 1

Φ (6) = 2

gcd (1, 6) is 1 and gcd (5, 6) is 1

Use the following Python to test Euler’s totient function on integers 1 through

20. The output should resemble Figure 4.3.

import math

def phi(n):

amount = 0

for k in range(1, n + 1):

if math.gcd(n, k) == 1:

amount += 1

return amount

for n in range(1,20) :

print("Φ(",n,") = ",phi(n))

To add a little pizzazz to your Python program, you can use the matplotlib

library and create a graph, as shown here:

import math

import numpy as np

from matplotlib import pyplot as plt

def phi(n):

amount = 0

for k in range(1, n + 1):

if math.gcd(n, k) == 1:

amount += 1

return amount

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!