This notebook was prepared by [Thunder Shiviah](https://github.com/ThunderShiviah). Source and license info is on [GitHub](https://github.com/ThunderShiviah/code_guild).
Primes are numbers which are only divisible by 1 and themselves.
5 is a prime since it can only be divided by itself and 1. 9 is not a prime since it can be divided by 3 (3*3 = 9). 1 is not a prime for reasons that only mathematicians care about.
To check if a number is prime, we can implement a basic algorithm, namely: check if a given number can be divided by any numbers smaller than the given number (note: you really only need to test numbers up to the square root of a given number, but it doesn't really matter for this assignment).
In [9]:
from math import sqrt, floor
def list_primes(n):
"""
Returns a list of prime numbers
takes an int and returns the primes up to and including that int
Parameters
----------
Input:
n: int
output:
prime: list
a list of integers
"""
prime = []
for i in range(2, n + 1):
for j in range(2, floor(sqrt(i) + 1)):
if i % j == 0:
break
else:
prime.append(i)
return prime
list_primes(11)
Out[9]:
In [76]:
from math import sqrt, floor, ceil
def list(n):
for i in range(2, n + 1):
for j in range(2, floor(sqrt(i + 1))):
print(i, j)
list(15)
The following unit test is expected to fail until you solve the challenge.
In [2]:
# %load test_list_primes.py
from nose.tools import assert_equal
class Test_list_primes(object):
def test_list_primes(self):
assert_equal(list_primes(1), [])
assert_equal(list_primes(2), [2])
assert_equal(list_primes(7), [2, 3, 5, 7])
assert_equal(list_primes(9), list_primes(7))
print('Success: test_list_primes')
def main():
test = Test_list_primes()
test.test_list_primes()
if __name__ == '__main__':
main()
Review the Solution Notebook for a discussion on algorithms and code solutions.
In [ ]: