Project Euler Problem #9 (R)
Problem 9 involves finding the Pythagorean triple where a+b+c=1000.
Pythagorean triples have lots of useful relationships that we can exploit. The ones we shall use to solve this problem are:
In this case, we take , and generate the triples as follows:
# Problem 9
# Pythagorean Triple
problem9 <- function() {
sum <- 0
a <- 0; b <- 0; c <- 0;
m <- 0
for (m in 1:1000) {
for (n in m:1000) {
a <- m^2-n^2
b <- 2*m*n
c <- n^2 + m^2
if (all(a^2 + b^2 == c^2, sum(a,b,c)==1000)) {
return(prod(a,b,c))
}
}
}
}