NumPy Project Euler Problem 6

Project Euler Problem 6 is perfect to demonstrate the power of NumPy. No loops are required and only a few lines of code.


1. Create an array with the first 100 natural numbers

First we will create a NumPy array of the numbers 1 – 100 with the arange function.



a = numpy.arange(101)

2. Sum the squares of the numbers

Second we will sum the squares of the numbers with the sum function.



sum_squares = numpy.sum(a ** 2)

3. Square the sum of the numbers

The NumPy ndarray class has a sum method, that we can use to sum the numbers in our array. After that calculate the square of the sum.



square_sum = a.sum() ** 2

Below is the complete solution.



import numpy
 
#The sum of the squares of the first ten natural numbers is,
#1 ** 2 + 2 ** 2 + ... + 10 ** 2 = 385
 
#The square of the sum of the first ten natural numbers is,
#(1 + 2 + ... + 10) ** 2 = 55 ** 2 = 3025
 
#Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 - 385 = 2640.
 
#Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
 
# 1. Create an array with the first 100 natural numbers
a = numpy.arange(101)
 
# 2. Sum the squares of the numbers
sum_squares = numpy.sum(a ** 2)
 
# 3. Square the sum of the numbers
square_sum = a.sum() ** 2
 
# Calculate the difference
print square_sum - sum_squares

 


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


Share




 •  0 comments  •  flag
Share on Twitter
Published on February 05, 2012 01:35
No comments have been added yet.