The mathematical puzzle from the weekend edition of Le Monde from a few weeks ago was not too hard to solve by induction but my R code failed miserably! The puzzle was as follows:

*A calculator is broken in such a way that it starts by exhibiting 0, then pressing 4, 6 or 0 keeps adding this figure to the right of the current number (if not zero), while pressing 2 divides the current number by 2. For instance, a possible sequence is*

0
4 [press 4]
46 [press 6]
23 [press 2]
230 [press 0]

* Is it possible to exhibit any integer?*

I thus wrote the simple R code

library(gsubfn)
digitBase=function(n){
strapply(as.character(n), ".", as.numeric)[[1]]
}
check=function(x){
step=0
xdigits=digitBase(x)
ok=sum(xdigits==0)+sum(xdigits==4)+sum(xdigits==6)
if (ok<length(xdigits)){
y=2*x
step=1+check(y)
}
step
}

which unfortunately runs very quickly into problems as can be seen by calling

> check(7)
Error in if (ok < length(xdigits)) { :
missing value where TRUE/FALSE needed
In addition: Warning messages:
1: In do.call(FUN, as.list(s[, j])) : NAs introduced by coercion
2: In do.call(FUN, as.list(s[, j])) : NAs introduced by coercion
3: In do.call(FUN, as.list(s[, j])) : NAs introduced by coercion

because the 2x…x2x7 value gets out of bounds…

Filed under: R, Statistics Tagged: Le Monde, mathematical puzzle

*Related*

To

**leave a comment** for the author, please follow the link and comment on his blog:

** Xi'an's Og » R**.

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:** Le Monde, mathematical puzzle, R, statistics