Here you will find daily news and tutorials about R, contributed by over 750 bloggers.
There are many ways to follow us - By e-mail:On Facebook: If you are an R blogger yourself you are invited to add your own R content feed to this site (Non-English R bloggers should add themselves- here)

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 a^{2} + b^{2} = c^{2}.

To solve this problem, we first see that c = (a^{2} + b^{2})^{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:

1234567891011

for(a in1:499){for(b in1: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(a^{2} + b^{2}) 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.

Related

To leave a comment for the author, please follow the link and comment on their blog: Frank Portman.