Project Euler in R Problem 9

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:

1
2
3
4
5
6
7
8
9
10
11
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))
     break
   }
 }
 if (a + b + sqrt(a^2 + b^2) == 1000) {
   break
 }
}

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.