Le Monde puzzle [#939bis]

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!

One Response to “Le Monde puzzle [#939bis]”

  1. Many thanks for the mention Christian

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s