[Project Euler] – Problem 58

[This article was first published on YGC, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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 their blog: YGC.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)