Tutorial
Tutorial#
We will here use a computer to gain some evidence to help tackle the following problem.
Problem
Consider the following polynomial:
Verify that \(p(n)\) is prime for \(n\in \mathbb{Z}\) up until \(n=20\).
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
You 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 you 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 was done 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]
You 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 you 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 you know how many
repetitions are necesary.
To answer the second question you 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 you do not know how many times a repetition
should be made but you know under what conditions it should be made.
Indeed for \(n=40\) you 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