Project Euler in R Problem 9

December 13, 2012

(This article was first published on Frank Portman, and kindly contributed to R-bloggers)

In Problem 9 of Project Euler we are tasked with finding the product (abc) of the Pythagorean Triplet (a, b, c) such that a + b + c = 1000.

A Pythagorean triplet is a set of three natural numbers such that a2 + b2 = c2.

To solve this problem, we first see that c = (a2 + b2)1/2. Without loss of generality, we can only run the for loop for a and b, since c will be uniquely determined given a certain a and b.

The code I used:

for (a in 1:499) {
 for (b in 1:499) {
   if (a + b + sqrt(a^2 + b^2) == 1000) {
     print(a * b * sqrt(a^2 + b^2))
 if (a + b + sqrt(a^2 + b^2) == 1000) {

I use nested for loops to test values of a and b between 1 and 499. a and b cannot take values greater than 499 because then a + b + sqrt(a2 + b2) would be greater than 1000.

The if statement in the nested loops checks to see whether a, b, and c add up to 1000. If they do, it prints their product and then breaks the loop. This is a short script which produces the correct answer in a few milliseconds. The trick here was expressing c in terms of a and b to reduce the amount of loops we need to run.

To leave a comment for the author, please follow the link and comment on their blog: Frank Portman. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)