# 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 Nov 29, 2015 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? Nov 29, 2015 at 19:35
– orlp
Nov 29, 2015 at 19:39
• I presume that using math to extract the bits also counts as binary conversion? Nov 29, 2015 at 20:23
• – user45941
Nov 29, 2015 at 23:47

## 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 Nov 29, 2015 at 18:57
• why does this answer have more votes than the answer with the least bytes? o_O Nov 29, 2015 at 19:56
• @Seadrus You know what they say. A picture is worth 7 bytes. Nov 29, 2015 at 20:03
• so your score is 42 + 7 = 49 bytes :P Nov 29, 2015 at 23:20
• Sorry, @CᴏɴᴏʀO'Bʀɪᴇɴ. Nov 30, 2015 at 10:09

# 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! Nov 29, 2015 at 20:40
• Also, w works the same on strings as it does on arrays, so you don't need the two as :) Nov 29, 2015 at 20:41
• One last thing: Us2  = ¢, and p2 = ², bringing it down to 7 bytes: ¢w n2 ² Nov 29, 2015 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...) Dec 1, 2015 at 4:17
• @ETHproductions - now I can +1 this :) Dec 2, 2015 at 23:11

## 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. Nov 30, 2015 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, 2015 at 10:58
• @orlp: Well, that's a bummer. I'm kinda convinced now that your bonus is impossible. Nov 30, 2015 at 20:18
• @El'endiaStarman I've almost got it, I think. Dec 3, 2015 at 18:41

# 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.

# Par, 5 bytes

✶Σ⌐Σ²


• I count 12 Dec 4, 2015 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, 2015 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, 2015 at 9:51
• Oh, I see. @orlp Dec 4, 2015 at 12:10
• Possibly it has its own SBCS? Apr 1, 2017 at 21:38

# 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. Nov 29, 2015 at 21:40
• @quartata Not as bad as a crossed out 4.
– orlp
Nov 29, 2015 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

• Does the interpreter understand any encodings other than UTF8? Using UTF8 encoding, I think your entry is 12 bytes long. Nov 30, 2015 at 20:37

## 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! Nov 29, 2015 at 21:28
• +1 for having your interpreter accept CP437 encoding (or at least the hex representation of it) Nov 30, 2015 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." Apr 1, 2017 at 19:38

## 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


# 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"+ Nov 29, 2015 at 18:45
• @Downgoat hm, it doesn't appear to give correct results. Nov 29, 2015 at 18:48
• [...n.toString(2)] and .join Nov 29, 2015 at 18:48
• Even shorter w/ ES7 (49 bytes): n=>+("0b"+[...n.toString(2)].reverse().join)**2. Doesn't work in any browsers yet Nov 29, 2015 at 19:08
• @CᴏɴᴏʀO'Bʀɪᴇɴ Thanks, this saves some bytes. Nov 29, 2015 at 19:45

echo pow(bindec(strrev(decbin($argv[1]))),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
$ # 05AB1E, 4 bytes bRCn  Try it online! # Explanation  Implicit input b Convert to binary R Reverse C Convert from binary n Square Implicit output  # MathGolf, 4 bytes àxå²  Try it online. Explanation: à # Convert the (implicit) input-integer to a binary-string x # Reverse this string å # Convert it from a binary-string back to an integer ² # Take the square of this integer # (after which the entire stack joined together is output implicitly as result)  # Wolfram Language (Mathematica), 40 bytes #+##&~Fold~Reverse@IntegerDigits[#,2]^2&  Try it online! # Vyxal, 4 bytes bṘB²  Try it Online! bṘB² bṘB # Convert to binary, reverse, convert back to decimal ² # Square  # Haskell, 38 bytes (#0) 0#s=s^2 n#s=div n 2#(2*s+nmod2) Attempt This Online! # 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). Nov 29, 2015 at 23:07 • I grade using UTF-8 (until I can get Mines encoding to work). Nov 29, 2015 at 23:12 • The... name of the language... is boxes? Nov 30, 2015 at 21:45 • It's ESMin in doublestruck. The Unicode chars aren't fully supported. Nov 30, 2015 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  # C (gcc), 38 bytes r;f(n){for(r=n%2;n/=2;r+=r+n%2);r*=r;}  Reverse all the bits, square the result. Pretty standard. -1 byte thanks to ceilingcat! Try it online! # Perl 5-p, 38 bytes $_=(oct"0b".reverse sprintf"%b",$_)**2  Try it online! # Splunk (v8.2.6) Search Processing Language, 182 170 bytes: |inputcsv b|foreach *[eval x=<<FIELD>>]|eval p=mvrange(0,floor(log(x,2)+1))|mvexpand p|eval x=floor(x/pow(2,p))%2|stats list(x) as x|eval x=tonumber(mvjoin(x,""),2),x=x*x  Big data. Smallish code. Am learning Splunk for work, and decided to try to have a bit of fun with it. Input is expected in a file at$SPLUNK_HOME/var/run/splunk/csv/b.csv. The file must contain the number in base 10 followed by a newline. The output is the search result, which is analogous to an SQL SELECT. This is as close to our standard I/O rules as I could reasonably do in SPL, but I'm willing to work something out if this is problematic.

With whitespace:

| inputcsv b
| foreach * [eval x=<<FIELD>>]
| eval p=mvrange(0,floor(log(x,2)+1))
| mvexpand p
| eval x=floor(x/pow(2,p))%2
| stats list(x) as x
| eval x=tonumber(mvjoin(x,""),2),x=x*x


Explanation (I plan to flesh this out more later):

| inputcsv b                             Read in b 
| foreach * [eval x=<<FIELD>>]           Get the value into a field "x" (Splunk reads our "CSV" file in as an event with one field, named the value we want, with a value of the empty string.) 
| eval p=mvrange(0,floor(log(x,2))+1)    Create a multivalue field "p" which contains the numbers 0 to the number of bits required to represent our number, the order here also means we get the reverse for free 
| mvexpand p                             Expand our single event with a multivalue field "p" into multiple events, each with a certain value of p 
| eval x=floor(x/pow(2,p))%2             Calculate (x/(2**p))%2, and set that value back to x
| stats list(x) as x                     Collect the values of x back into a single multivalue event 
| eval x=tonumber(mvjoin(x,""),2),x=x*x  Combine all the bits back into a string, and convert that string back into a numeric value, then square it
result is a single event with field x, containing the square of the bit reversed input.


Edit: forgot how math works (ceil instead of floor + 1 for the bit length calculation), and managed to only check with inputs that worked with my wrong math. Also sort happened to be a leftover from when I was doing the problem more verbosely, we get the reverse sort for free. Nets to -12.

# Desmos, 124 72 bytes

f(n)=total(mod(floor(n/2^l),2)2^k/2^l)^2
k=floor(log_2(n+0^n))
l=[k...0]


Try it on Desmos!

-52 bytes thanks to Aiden Chow

# LOLCODE, 192 bytes

HAI 1.3
I HAS A s ITZ 0
I HAS A x
GIMMEH x
IM IN YR l
s R SUM OF PRODUKT OF s 2 MOD OF x 2
x R QUOSHUNT OF x 2
BOTH SAEM x 0,O RLY?
YA RLY
GTFO
OIC
IM OUTTA YR l
VISIBLE PRODUKT OF s s
KTHXBYE


Try it online!

# cQuents, 10 bytes

K\rJ$)))^2  Try it online! First time using cQuents. ## Explanation $      # Take the index.
J )     # Convert to (default) base 2.
\r   )    # Reverse it.
K      )   # Convert from (default) base 2 to base 10.
^2 # And square it.