# Reverse and square

In this challenge you will compute numbers from a curious sequence.

Your input is a single decimal nonnegative integer. Reverse the bits in this integer and then square the number to get the required output.

When reversing the bits you must not use any leading zeroes in the input. For example:

26 (base 10) = 11010 (base 2) -> 01011 (base 2) = 11 -> 11*11 = 121


The first 25 inputs/outputs of this sequence:

0: 0
1: 1
2: 1
3: 9
4: 1
5: 25
6: 9
7: 49
8: 1
9: 81
10: 25
11: 169
12: 9
13: 121
14: 49
15: 225
16: 1
17: 289
18: 81
19: 625
20: 25
21: 441
22: 169
23: 841
24: 9


Your solution should work for arbitrarily sized integers. If your language does not have a convenient built-in method of using those, implement your answer as if it does. You are then excused if your answer breaks for large numbers. However, do not use tricks/bounds that only work for a limited domain (such as a lookup table).

Your score is the number of bytes of source code.

-50% bonus if you never convert the number to/from binary. This is not limited to builtins, if you loop over the number bit by bit (either by shifting or masking or any other method), it will also count as conversion. I don't know whether this is actually possible, but it gives an incentive to spot a pattern in the sequence.

Smallest score wins.

• So close – Conor O'Brien Nov 29 '15 at 18:54
• If the code calls a method that results in a character string that represents the bits, is that eligible for the bonus? – Brad Gilbert b2gills Nov 29 '15 at 19:35
• @BradGilbertb2gills No. – orlp Nov 29 '15 at 19:39
• I presume that using math to extract the bits also counts as binary conversion? – lirtosiast Nov 29 '15 at 20:23
• – Mego Nov 29 '15 at 23:47

# Par, 5 bytes

✶Σ⌐Σ²


• I count 12 – Conor O'Brien Dec 4 '15 at 3:52
• @CᴏɴᴏʀO'Bʀɪᴇɴ That byte counter assumes UTF-8. I believe Mauris is using some encoding that is not UTF-8 to count his bytes, but he did not specify this encoding. – orlp Dec 4 '15 at 9:16
• Par uses its own weird encoding. Its canonical representation is a certain subset of <256 Unicode characters. I'm not sure if it has a name; I should wait for @Ypnypn to chime in. – Lynn Dec 4 '15 at 9:51
• Oh, I see. @orlp – Conor O'Brien Dec 4 '15 at 12:10
• Possibly it has its own SBCS? – HyperNeutrino Apr 1 '17 at 21:38

## Mathematica, 42 21 bytes

Thanks to alephalpha for halving the score.

#~IntegerReverse~2^2&


The actual reason I did this in Mathematica was because I wanted to look at a plot... it sure looks funny: • But I like the score! XD – Conor O'Brien Nov 29 '15 at 18:57
• why does this answer have more votes than the answer with the least bytes? o_O – Seadrus Nov 29 '15 at 19:56
• @Seadrus You know what they say. A picture is worth 7 bytes. – Martin Ender Nov 29 '15 at 20:03
• so your score is 42 + 7 = 49 bytes :P – Seadrus Nov 29 '15 at 23:20
• Sorry, @CᴏɴᴏʀO'Bʀɪᴇɴ. – Martin Ender Nov 30 '15 at 10:09

## Minkolang 0.14, 43 bytes

Thanks to Mego for inspiring this.

n1{d1,2$3*&$z2zd2%-2l$Md1%-;z2%*z2:{+}2;N.  ### Explanation This uses this recurrence relation: a(0) = 0 a(1) = 1 a(2n) = a(n) a(2n+1) = a(n) + 2^(floor(log_2(n))+1)  If n is the input, then a(n) is the resulting number after its binary sequence has been flipped. 0 and 1 are obvious. For a(2n) = a(n), consider that x0 (where x is any sequence of binary digits) flipped is 0x, which is the same as x. For a(2n+1), the reasoning is a bit more complicated. x1 flipped is 1x, which is equal to x + 2^k for some k. This k is one more than the number of digits in x, which is floor(log_2(n))+1. The full formula follows, except that it's modified a bit. This is what I actually code: a(0) = 0 a(1) = 1 a(n) = a(n//2) + (n%2) * 2^(floor(log_2(n - n%2)))  As Mego and I worked out in chat, floor(n/2) = (n - n%2)/2. Thus, log_2(floor(n/2))+1 = log_2(n - n%2). Furthermore, multiplying by (n%2) collapses both the odd and even parts into one expression. Finally, without any further ado, here's the code, explained. n Take number from input 1{ Start recursion that takes only one element d1, 1 if top of stack 0 or 1, 0 otherwise 2$3*                                    26
&                                   Jump if top of stack is not zero
$z Store top of stack in register (z) zd2%- n - n%2 2l$M                       log_2(n - n%2)
d1%-                   floor(log_2(n - n%2))
2             ;                  2^floor(log_2(n - n%2))
z2%               n%2
*              Multiply
z2:           n//2
{          Recurse
}        Return
2;N.    Square it, output as number, and stop.

• I think the recurrence is just a reformulation of iterating over the individual bits. – Martin Ender Nov 30 '15 at 10:11
• I'm afraid this doesn't count. Whenever you see 2n and 2n+1 in a recurrence relation you should immediately think of it as looping over bits. – orlp Nov 30 '15 at 10:58
• @orlp: Well, that's a bummer. I'm kinda convinced now that your bonus is impossible. – El'endia Starman Nov 30 '15 at 20:18
• @El'endiaStarman I've almost got it, I think. – Conor O'Brien Dec 3 '15 at 18:41

# Japt, 292811 7 bytes

(You can save the program as a 7-byte IEC_8859-1-encoded file, then upload it to the interpreter.)

Japt is shortened JavaScript made by ETHproductions.

¢w n2 ²


Try it online!

Explanation:

1. ¢ is shortcut to Us2, which compiles to U.s(2). U is input (implicit), .s(2) called by a number, invokes .toString(2) (converts to binary, parses as string).

2. w compiles to .w(), which reverses the string (.split('').reverse().join('')).

3. n2 works as parseInt(<number>,2), i.e. converts binary to decimal.

4. ² invokes Math.pow(<number>,2), i.e. squares the number.

• There's a string function toNumber on n, so you could do Us2 a w a n2 p2. Good job though! – ETHproductions Nov 29 '15 at 20:40
• Also, w works the same on strings as it does on arrays, so you don't need the two as :) – ETHproductions Nov 29 '15 at 20:41
• One last thing: Us2  = ¢, and p2 = ², bringing it down to 7 bytes: ¢w n2 ² – ETHproductions Nov 29 '15 at 20:44
• The online interpreter now accepts IEC_8859-1 encoded files. (Although I'm not sure how to do UTF-8 and UTF-16 as well...) – ETHproductions Dec 1 '15 at 4:17
• @ETHproductions - now I can +1 this :) – Digital Trauma Dec 2 '15 at 23:11

# Python, 32 bytes

lambda x:int(bin(x)[:1:-1],2)**2


Try it online.

The code is pretty straightforward: bin(6), for example, gives 0b110, the binary representation of 6. [:1:-1] reverses the string and removes 0b. int converts the string to an integer from binary, and **2 squares it.

# Jolf, 7 bytes

Just run it. The input on the page doesn't work.

^C_Bj22


## Explanation

^C_Bj22
j   numeric input
B    convert to binary (str)
_     reverse
C   2  parse as binary integer to base 10
^     2 square
implicit output


I added the Q command, which makes this 6 bytes: QC_Bj2

• Crossed out 7 still looks like a 7. – a spaghetto Nov 29 '15 at 21:40
• @quartata Not as bad as a crossed out 4. – orlp Nov 29 '15 at 21:51

# TeaScript, 9 bytes11

TeaScript is Javascript for golfing

®x÷v¤)**2


Will golf more once I get back to my computer

Try it online!

Test all

## Seriously, 8 7 bytes

2;,¡R¿ª


Challenges like these are perfect for Seriously :)

Try it online

Explanation:

2;,¡    get a string representing the (decimal) input in binary, with a 2 on the bottom of the stack
R      reverse the string
¿    convert binary string to decimal int (using that extra 2 from earlier)
ª      square it

• Nice job matching Jolf! – Conor O'Brien Nov 29 '15 at 21:28
• +1 for having your interpreter accept CP437 encoding (or at least the hex representation of it) – Digital Trauma Nov 30 '15 at 20:49

# J, 10 9 bytes

2^~|.&.#:


This is a tacit, monadic verb. Try it online!

Thanks to @randomra for golfing off 1 byte!

### How it works

2^~|.&.#:  Right argument: y

#:  Convert y to binary.
|.      Reverse the digits.
&.    Dual; apply the inverse of #:, i.e., convert back to integer.
^~        Apply power (^) with reversed argument order (~)...
2          to 2 and the previous result.

• Link doesn't work, I get a 404 error on a google page that says "The requested URL /host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html was not found on this server. That’s all we know." – Bijan Apr 1 '17 at 19:38

# CJam, 10 bytes

ri2bW%2b_*


Try it online

# JavaScript, 646356 53 bytes

n=>parseInt([...n.toString(2)].reverse().join,2)**2


I realize I'm extra long, but hey, I can do it :P

Demo

• instead of parseInt( you can do +("0b"+ – Downgoat Nov 29 '15 at 18:45
• @Downgoat hm, it doesn't appear to give correct results. – nicael Nov 29 '15 at 18:48
• [...n.toString(2)] and .join – Conor O'Brien Nov 29 '15 at 18:48
• Even shorter w/ ES7 (49 bytes): n=>+("0b"+[...n.toString(2)].reverse().join)**2. Doesn't work in any browsers yet – Downgoat Nov 29 '15 at 19:08
• @CᴏɴᴏʀO'Bʀɪᴇɴ Thanks, this saves some bytes. – nicael Nov 29 '15 at 19:45

## Perl 6, 21 bytes

{:2(.base(2).flip)²}


Example usage:

say {:2(.base(2).flip)²}(26); # 121

say (0..24).map: {:2(.base(2).flip)²};
# (0 1 1 9 1 25 9 49 1 81 25 169 9 121 49 225 1 289 81 625 25 441 169 841 9)

my &code = {:2(.base(2).flip)²};
say code 3; # 9

say chars code 10¹⁰⁰; # 140


echo pow(bindec(strrev(decbin($argv))),2);  # Shell, 25 dc -e2o?p|rev|dc -e2i?d*p  Input/output via STDIN/STDOUT: $ echo 26|dc -e2o?p|rev|dc -e2i?d*p
121
\$


# Pyth - 9 bytes

Straightforward conversions. I actually assigned 2 to a var which is pretty weird.

^i_jQK2KK


## Pyth, 9 bytes

^i_.BQ2 2


This is a very simple pyth based answer similar to the Python one

# 𝔼𝕊𝕄𝕚𝕟, 12 chars / 21 bytes

⦅ᶀ+ᴙ(ïß2)²


Try it here (Firefox only).

## Noncompetitive answer, 9 chars / 18 bytes

⦅Յ+ᴙ(ïⓑ)²


Try it here (Firefox only).

• Via this byte counter, gives 15 bytes (uses another encoding). – nicael Nov 29 '15 at 23:07
• I grade using UTF-8 (until I can get Mines encoding to work). – Mama Fun Roll Nov 29 '15 at 23:12
• The... name of the language... is boxes? – corsiKa Nov 30 '15 at 21:45
• It's ESMin in doublestruck. The Unicode chars aren't fully supported. – Mama Fun Roll Nov 30 '15 at 23:41

# Ruby, 35 bytes

->(x){x.to_s(2).reverse.to_i(2)**2}


# TI-Basic (TI-84 Plus CE), 42 bytes

Prompt X
0→S
While X
2S→S
If X/2≠int(X/2
S+1→S
End
S2