[Project Euler] – Problem 58

May 21, 2011
By

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

Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed.

37 36 35 34 33 32 31
38 17 16 15 14 13 30
39  18  5 4  3 12  29
40  19  6   1  2  11  28
41 20   7 8   9  10  27
42 21 22 23 24 25 26
43 44 45 46 47 48 49

It is interesting to note that the odd squares lie along the bottom right diagonal, but what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%.

If one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. If this process is continued, what is the side length of the square spiral for which the ratio of primes along both diagonals first falls below 10%?

?View Code RSPLUS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
side.length = 1
x <- 1
iter <- 1
ratio = 0.6
isp.n <- 0
N <- 0
while(ratio > 0.1) {
	last.x <- x[length(x)]
	side.length <- side.length + 2
	x <- rep(last.x,4 ) + c(2,4,6,8)* iter
	iter <- iter + 1
	isp <- gmp::isprime(x)
	isp.n <- isp.n + sum(as.logical(isp))
	N <- N + 4
	ratio <- isp.n/N
	print(side.length)
}

Answer: 26241

Related Posts

To leave a comment for the author, please follow the link and comment on his blog: YGC.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: 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...

Tags: , , ,

Comments are closed.