Categories
Coding Project Euler R

Project Euler Problem #28

Problem 28 on the Project Euler website asks what is the sum of both diagonals in a 1001×1001 clockwise spiral. This was an interesting one: the relationship between the numbers on the diagonals is easy to deduce, but expressing it succinctly in R took a little bit of tweaking. I’m sure it could be compressed even further.

[sourcecode lang=”r”]
spiral.size <- function(n) {
stopifnot(n %% 2 ==1)

if (n==1) {
return(1)
}
sum(cumsum(rep(2*seq(1,floor(n/2)), rep(4,floor(n/2))))+1)+1
}

spiral.size(1001)
[/sourcecode]