Tutorial#

We will here use a computer to gain some evidence to help tackle the following problem.

Problem

Consider the following polynomial:

\[ p(n) = n ^ 2 + n + 41 \]
  1. Verify that \(p(n)\) is prime for \(n\in \mathbb{Z}\) up until \(n=20\).

  2. What is the smallest value of \(n\) for which \(p(n)\) is no longer prime?

We will start by defining a function for \(p(n)\):

def p(n):
    """
    Return the value of n ^ 2 + n + 41 for a given value of n.
    """
    return n ** 2 + n + 41

We will use sympy to check if a number is prime.

import sympy as sym

sym.isprime(3)
True
sym.isprime(4)
False

Now to answer the first question we will use a list comprehension to create a list of boolean variables that confirm if \(p(n)\) is prime.

Tip

This is similar to what we did in Probability.

checks = [sym.isprime(p(n)) for n in range(21)]
checks
[True,
 True,
 True,
 True,
 True,
 True,
 True,
 True,
 True,
 True,
 True,
 True,
 True,
 True,
 True,
 True,
 True,
 True,
 True,
 True,
 True]

We can use the all tool to check if all the boolean values are true:

all(checks)
True

Attention

Using list comprehensions is a mathematical way of repeating code but at times it might prove useful to repeat code in a different way using a standard for statement.

In that case we can essentially repeat the previous exercise using:

checks = []
for n in range(21):
    value = p(n)
    is_prime = sym.isprime(value)
    checks.append(is_prime)
all(checks)
True

The main difference between the two approaches is that we can include multiple lines of indented code to be repeated for every value of n in range(21).

Attention

A for loop or a list comprehension should be used when we know how many repetitions we want to make.

To answer the second question we will repeat the code until the value of \(p(n)\) is no longer prime.

n = 0
while sym.isprime(p(n)):
    n += 1
n
40

Attention

A while loop should be used when we do not know how many times a repetition should be made but we know under what conditions is should be made

Indeed for that value of \(n\) we have:

p(n)
1681

and

sym.isprime(p(n))
False

sympy can also factor the number for us:

sym.factorint(p(n))
{41: 2}

Indeed:

41 ** 2
1681