This document summarizes the steps to solve Project Euler Problem 5 using NumPy:
1. Create an array of divisors from 11 to 20 to check for remainders against.
2. Use NumPy's all function to check if the remainder of a number divided by each divisor is 0.
3. Assert the solution is correct by checking for zero remainders against numbers from 2 to 20.
This document summarizes the steps to solve Project Euler Problem 5 using NumPy:
1. Create an array of divisors from 11 to 20 to check for remainders against.
2. Use NumPy's all function to check if the remainder of a number divided by each divisor is 0.
3. Assert the solution is correct by checking for zero remainders against numbers from 2 to 20.
Project Euler Problem 5is one of those problems that seem hard, but turn out to be trivial after you think about them. In this case it is very important to use the information given to you in the problem. This means using the fact that 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. We can therefore limit our search to multiples of 2520.
1. Create a divisors array
First we will create a divisors array. We only need to divide by the numbers 11 20. divisors = numpy.arange(11, 21)
2. Check for 0 remainder
Second make sure that all the divisions of a number by the divisors produce a 0 remainder. We can check for that with the NumPy all function. numpy.all((i % divisors) == 0)
3. Test the solution
Eventually we will get an answer. We need to check whether this is the correct answer. Use the assert_equal function from the numpy.testing module to confirm the result. numpy.testing.assert_equal(numpy.zeros(19), i % numpy.arange(2, 21))
Below is the complete code solution.
import numpy #2520 is the smallest number that can be divided by each of the numbers from 1 t o 10 without any remainder. #What is the smallest positive number that is evenly divisible by all of the num bers from 1 to 20? # 1. Create a divisors array divisors = numpy.arange(11, 21) for i in xrange(2520, 10 ** 9, 2520): # 2. Check for 0 remainder if numpy.all((i % divisors) == 0): print i # 3. Test the solution numpy.testing.assert_equal(numpy.zeros(19), i % numpy.arange(2, 21)) break
If you liked this post and are interested in NumPy check out NumPy Beginners Guide by yours truly.