NumPy Project Euler Problem 1

This entry is part 1 of 9 in the series NumPy Project Euler

Project Euler is a website that lists a number of mathematical problems, which are perfect to be solved with NumPy. Let’s 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 get 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 Beginner’s Guide by yours truly.

Series NavigationNumPy Project Euler Problem 2
By the author of NumPy Beginner's Guide, NumPy Cookbook and Instant Pygame. If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.
Share
This entry was posted in programming and tagged , . Bookmark the permalink.