NumPy Project Euler Problem 6

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

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.

Series NavigationNumPy Project Euler Problem 5NumPy Project Euler Problem 7
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.