You are on page 1of 2

ivanidris.

net

NumPy Project Euler Problem 1


Project Euler is a website that lists a number of mathematical problems, which are perfect to be solved with NumPy. Lets start the new year with Problem 1.

1. Call the arange function


Call the arange function in order to store all the integers from 1 to 1000 in an array.
# 1. Numbers 1 - 1000 a = numpy.arange(1, 1000)

2. Select the multiples of 3 or 5


Select using the [] operator.
# 2. Select multiple of 3 or 5 a = a[(a % 3 == 0) | (a % 5 == 0)] print a[:10]

This prints as expected


[ 3 5 6 9 10 12 15 18 20 21]

3. Sum the array elements


Call the sum method on the NumPy array.
# 3. Sum the numbers print a.sum()

Once again the code below in its entirety.


import numpy #Problem 1. #If we list all the natural numbers below 10 that are multiples of 3 or 5, we ge t 3, 5, 6 and 9. #The sum of these multiples is 23. #Find the sum of all the multiples of 3 or 5 below 1000. # 1. Numbers 1 - 1000 a = numpy.arange(1, 1000) # 2. Select multiple of 3 or 5 a = a[(a % 3 == 0) | (a % 5 == 0)] print a[:10] # 3. Sum the numbers print a.sum()

If you liked this post and are interested in NumPy check out NumPy Beginners Guide by yours truly.

You might also like