Le Monde puzzle [#939bis]

[This article was first published on Xi'an's Og » R, 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.

If you remember the previous post, I had two interpretations about Le Monde mathematical puzzle #639:

Find all integers with less than 11 digits that are perfect squares and can be written as a(a+6), a being an integer.

and:

Find all integers with less than 11 digits that are perfect squares and can be written as x concatenated with (x+6), x being an integer.

I got a nice email from Jamie Owen, from Newcastle, Britain, about an R resolution with a clever code, as opposed to mine!

About the second version of the puzzle, Jamie first creates the vector of concatenations:

 
x = 1:1e5
cats = x * (10^floor(log10(x+6) + 1) +1)+ 6

He then made the function perfect more… perfect:

perfect=function(b){
  a=trunc(sqrt(b))
  any((a:(a+1))^2 == b)
  }

(using a function any() I had not seen before, and then got the collection of solutions as

x = 1:1e5
x[sapply(x * (10^floor(log10(x+6) + 1) +1)+ 6,perfect)]
[1] 15 38

which runs about 25 times faster than my R solution! (And he further designed a 100 times faster version…)

Jamie also proposed an R code for solving the first version of that puzzle:

max = 1e10
squares = (1:floor(sqrt(max)))^2
# possible answers to a(a+6)
a = -1e6:1e6
# which squares have solutions
sols = intersect(a*(a + 6), squares)
# what are they?
f = function(x){
power = floor(floor(log10(x))/2)+1
a = -10^power:10^power
sols = c(x,a[a*(a+6) - x == 0])
names(sols) = c("square", "a1", "a2")
sols
}
sapply(sols,f)
## [,1]
## square 16
## a1 -8
## a2 2

which returns again 2 as the unique positive solution (equivalent to -8, if considering relative integers). A great lesson in efficient R programming, thanks Jamie!


Filed under: Books, Kids, R Tagged: arithmetics, as.character(), as.numeric(), fast code, Le Monde, mathematical puzzle, R, strsplit()

To leave a comment for the author, please follow the link and comment on their blog: Xi'an's Og » R.

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)