Week 4 notebook

In [49]:
import matplotlib.pyplot as plt
In [2]:
xlist = [1, 2, 3]
ylist = [0, 1, 7]
In [10]:
plt.plot(xlist, ylist, 'g--', ms=20, alpha=0.5)
plt.show()

Project 2: Pythagorean triples

Definition A Pythagorean triple is a triple of positive integers $(a, b, c)$ such that $$a^2 + b^2 = c^2 $$

Example: (3, 4, 5) is a Pythagorean triple.

Exercise Write a function issquare(n) that returns True if n is a square of some integer and False otherwise.

In [57]:
def issquare(n):
    return n**0.5 == round(n**0.5)
In [58]:
issquare(4)
Out[58]:
True
In [59]:
issquare(100)
Out[59]:
True
In [15]:
issquare(101)
Out[15]:
False
In [16]:
squares = [n for n in range(101) if issquare(n)]
print(squares)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
In [63]:
def ptriples(n):
    pt = []
    for a in range(1, n+1):
        for b in range(1, n+1):
            if issquare(a**2 + b**2):
                pt.append([a, b, int((a**2 + b**2)**0.5)])
    return pt
In [64]:
print(ptriples(20))
[[3, 4, 5], [4, 3, 5], [5, 12, 13], [6, 8, 10], [8, 6, 10], [8, 15, 17], [9, 12, 15], [12, 5, 13], [12, 9, 15], [12, 16, 20], [15, 8, 17], [15, 20, 25], [16, 12, 20], [20, 15, 25]]
In [51]:
pt = ptriples(500)
alist = [triple[0] for triple in pt]
blist = [triple[1] for triple in pt]

plt.figure(figsize=(10,10))
plt.plot(alist, blist, 'r.')
plt.show()

Note: The lines show up because multiples of Pythagorean triples are Pythagorean triples.

In [56]:
t = [8, 15, 17] # Pythagorean triple
a_mult = [t[0]*n for n in range(1, 30)] # list of multiples of the first element of t
b_mult = [t[1]*n for n in range(1, 30)] # list of multiples of the second element of t

plt.figure(figsize=(10,10))
plt.plot(a_mult, b_mult, 'co', ms=12)

pt = ptriples(500)
alist = [triple[0] for triple in pt]
blist = [triple[1] for triple in pt]
plt.plot(alist, blist, 'r.')

plt.show()

Definition A Primitive Pythagorean triple is a Pythogorean triple $(a, b, c)$ such that $gcd(a, b) = 1$.

The greatest common divisor

$\gcd(a, b)$ is the greatest integer that divides both $a$ and $b$.

If $\gcd(a, b)= 1$ then we say that $a$ and $b$ are relatively prime.

Euclidean algorithm for computing gcd

  • start with two integers a, b
  • subtract the smaller number from the larger
  • repeat until one of the numbers becomes 0
  • the other number is the the $\gcd(a, b)$