## (x=scan())%in%(2*4^(n=0:x)-2^n-1) One challenge on code golf is to find the shortest possible code to identify whether or not an integer belongs to the binary cyclops numbers which binary expansion is 0, 101, 11011, 1110111, 111101111, &tc. The n-th such number being $a(n) = 2^{2n + 1} - 2^n - 1 = 2\,4^n - 2^n - 1 = (2^n - 1)(2\,2^n + 1)$

this leads to the above solution in R (26 bits). The same length as the C solution [which I do not get]

f(n){n=~n==(n^=-~n)*~n/2;}

And with shorter versions in many esoteric languages I had never heard of, like the 8 bits Brachylog code

ḃD↔Dḍ×ᵐ≠

or the 7 bits Jelly

B¬ŒḂ⁼SƊ

As a side remark, since this was not the purpose of the game, the R code is most inefficient in creating a set of size (x+1), with most terms being Inf.

### 7 Responses to “(x=scan())%in%(2*4^(n=0:x)-2^n-1)”

1. […] discovered codegolf on Stack Exchange a few weeks ago, I spotted a few interesting puzzles since then but only got the […]

2. an attempt at code golf | R-bloggers Says:

[…] discovered codegolf on Stack Exchange a few weeks ago, I spotted a few interesting puzzles since then but only got the […]

3. Martyn Says:

This is the closest I can get to the logic of the C solution in R. Hoping this survives the forum software:

cyclops = function(n) {m=bitwXor(n,n+1);n==(m+2)*floor(m/2)}

If n=(2^k-1)*(2^(k+1)+1), then using the binary representation of integers, a bitwise exclusive OR comparison between n and n+1 gives us m=2^(k+1)-1. So m+2 gives the larger factor and floor(m/2) the smaller one. If we can reconstruct n from its factors then it is a cyclops number.

You can shave off a few characters, avoiding brackets and the floor function with:

cyclops = function(n) {m=bitwXor(n,n+1);2*n+2==m*m+m}

The C code is extremely compact because bit-wise operators are built in (we need the bitwXor function), you can rely on integer arithmetic (R coerces to double), and you can overwrite the input in the middle of an expression (you can’t do this in a functional language).

• xi'an Says:

Thank you Martyn! Makes more sense to me than the C solution. But can you gain a few bytes by not using a function and scan() instead?

• Martyn Says:

Here’s a version with scan().

m=bitwXor(n<-scan(),n+1);n==(m+2)*(m-1)/2

This is vectorized so you can give as many numbers as you want.

• xi'an Says:

42 bytes, just a wee bit above the R solution of 26 bytes!

4. (x=scan())%in%(2*4^(n=0:x)-2^n-1) | R-bloggers Says: