Reverse and square

19

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.

orlp

Posted 2015-11-29T18:34:42.417

Reputation: 37 067

6So close – Conor O'Brien – 2015-11-29T18:54:14.680

1If the code calls a method that results in a character string that represents the bits, is that eligible for the bonus? – Brad Gilbert b2gills – 2015-11-29T19:35:55.460

2@BradGilbertb2gills No. – orlp – 2015-11-29T19:39:34.553

I presume that using math to extract the bits also counts as binary conversion? – lirtosiast – 2015-11-29T20:23:27.047

@ThomasKwa Yes. – orlp – 2015-11-29T20:32:57.707

If the code converts to a hex string, then uses magic to reverse bits in each nybble, then reverses all nybbles in the hex string, does that qualify for the bonus? – Digital Trauma – 2015-11-29T21:36:42.370

@DigitalTrauma No. Only a radically different approach (such as a closed algebraic form) qualifies for the bonus. As I've said in the question - I'm not certain whether that's possible at all. – orlp – 2015-11-29T21:49:37.227

Can I use binary conversion if I'm converting a separate result? (For the bonus) – Conor O'Brien – 2015-11-29T23:17:55.713

2Relevant and relevant – Mego – 2015-11-29T23:47:02.243

This challenge is conversion-to-bits away from a Dock Length 5 Fishing solution: IrnSP.

– Arcturus – 2015-11-30T05:16:02.017

I take it partitioning a number into powers of 2 (e.g. using Mathematica's IntegerPartition) also counts as conversion to binary? – Martin Ender – 2015-11-30T10:30:51.603

@MartinBüttner Yes. – orlp – 2015-11-30T10:57:45.673

Answers

5

Par, 5 bytes

✶Σ⌐Σ²

That's read-binary-reverse-binary-square.

Lynn

Posted 2015-11-29T18:34:42.417

Reputation: 55 648

I count 12 – Conor O'Brien – 2015-12-04T03:52:09.517

@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 – 2015-12-04T09:16:42.597

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 – 2015-12-04T09:51:11.970

Oh, I see. @orlp – Conor O'Brien – 2015-12-04T12:10:57.227

Possibly it has its own SBCS? – HyperNeutrino – 2017-04-01T21:38:53.293

19

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:

enter image description here

Martin Ender

Posted 2015-11-29T18:34:42.417

Reputation: 184 808

11But I like the score! XD – Conor O'Brien – 2015-11-29T18:57:57.347

1why does this answer have more votes than the answer with the least bytes? o_O – Seadrus – 2015-11-29T19:56:23.690

27@Seadrus You know what they say. A picture is worth 7 bytes. – Martin Ender – 2015-11-29T20:03:17.247

1Nice plot. The distribution does not look too surprising to me. You would expect the range of results to quadruple every time the input reaches a new power of 2 (i.e. has an additional bit). Then, within that range, the values are sort of randomly distributed, with a bias to lower values since the result is the square of a uniformly distributed value. – Reto Koradi – 2015-11-29T20:50:41.667

@RetoKoradi Actually, since trailing zeroes of the input are ignored, it's not quite uniform and even more biased to lower values :P – Sp3000 – 2015-11-29T21:54:50.683

5so your score is 42 + 7 = 49 bytes :P – Seadrus – 2015-11-29T23:20:13.507

@Sp3000 I think that's part of the uniformity. For each binary length, we get every odd number up to that length exactly once. – Martin Ender – 2015-11-29T23:21:59.767

#~IntegerReverse~2^2& – alephalpha – 2015-11-30T03:40:15.350

@alephalpha ah nice, I forgot that takes a base. – Martin Ender – 2015-11-30T06:31:14.917

3Sorry, @CᴏɴᴏʀO'Bʀɪᴇɴ. – Martin Ender – 2015-11-30T10:09:25.693

@MartinBüttner Oh well. 21 is okay in its own right ;) – Conor O'Brien – 2015-11-30T12:26:16.247

Good money says it shelves again after 1024. I wonder how the distribution compares to true uniform distribution after culling some of the condensed clusters at the bottom. Does the shelving hold up in base 3? base 10? I'd be interested to see it. – DoctorHeckle – 2015-11-30T16:53:40.520

@Seadrus Because it's insightful and interesting! – corsiKa – 2015-11-30T21:43:47.540

1@corsiKa 12 votes more insightful? – Seadrus – 2015-11-30T22:11:15.580

Mathematica is not specifically designed for golfing like the languages that usually win these kinds of competitions, which makes this answer more impressive than those in some ways. – corsiKa – 2015-11-30T22:12:34.470

1@Seadrus jokes aside, the shortest solution is no more interesting or impressive than any other solution, because they all us the same approach and it's only shortest due to having short built-ins for parts of the solution. In that sense, the plot does give this answer the edge. – Martin Ender – 2015-11-30T22:35:02.623

1right. but in another sense, this is a code-golf question – Seadrus – 2015-12-01T00:34:17.450

8

Japt, 29 28 11 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.

nicael

Posted 2015-11-29T18:34:42.417

Reputation: 4 585

1There's a string function toNumber on n, so you could do Us2 a w a n2 p2. Good job though! – ETHproductions – 2015-11-29T20:40:43.823

1Also, w works the same on strings as it does on arrays, so you don't need the two as :) – ETHproductions – 2015-11-29T20:41:38.920

1One last thing: Us2 = ¢, and p2 = ², bringing it down to 7 bytes: ¢w n2 ² – ETHproductions – 2015-11-29T20:44:24.663

I get 9 bytes here. Surely ¢ and ² are 2 bytes each according to this utf8 table. Or are you using some other weird encoding or codepage?

– Digital Trauma – 2015-11-30T05:39:23.253

@Dig it's seven bytes per this encoding https://en.m.wikipedia.org/wiki/ISO/IEC_8859. I've linked the interpreter I used - http://bytesizematters.com/.

– nicael – 2015-11-30T08:49:43.083

@nicael I've used that interpreter before and was called out on it.

– Conor O'Brien – 2015-11-30T16:19:33.320

@Cᴏɴᴏʀ Ok, as it's considered invalid to use anything other than UTF-8, I've stated it's 9 bytes, so as not to be considered a cheater. – nicael – 2015-11-30T16:23:05.680

@nicael If my understanding of IEC_8859 encoding is correct (I may be wrong), I think your program encoded accordingly is the output of echo -n a277206e3220b2 | xxd -p -r. If I paste this into the online interpreter I get "SyntaxError: Unexpected token ILLEGAL". The UTF8 encoding can be generated with echo -n c2a277206e3220c2b20a | xxd -p -r and works fine. If you have an interpreter that understands the IEC_8859 encoding, then I'm fine with you claiming 7 bytes. – Digital Trauma – 2015-11-30T20:22:46.080

3

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 – 2015-12-01T04:17:39.730

2@ETHproductions - now I can +1 this :) – Digital Trauma – 2015-12-02T23:11:53.603

@ETHproductions The online interpreter breaks in IE on tablet. – Conor O'Brien – 2015-12-03T18:40:38.110

@CᴏɴᴏʀO'Bʀɪᴇɴ I'd arranged the site so that it looked good on my screen, but maybe not many others. This should be fixed now. Is that what you meant by "breaks"? – ETHproductions – 2015-12-04T03:48:08.230

@ETHproductions It's beautiful :D – Conor O'Brien – 2015-12-04T03:48:39.080

@CᴏɴᴏʀO'Bʀɪᴇɴ Great, glad you like it :) BTW, nicael, I've added a section on Unicode shortcuts. – ETHproductions – 2015-12-04T03:50:55.900

8

Minkolang 0.14, 43 bytes

Thanks to Mego for inspiring this.

n1{d1`,2$3*&$z2zd2%-2l$Md1%-;z2%*z2:{+}2;N.

Test the code here and check all test cases here.

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
                                     +         Add
                                      }        Return
                                       2;N.    Square it, output as number, and stop.

El'endia Starman

Posted 2015-11-29T18:34:42.417

Reputation: 14 504

1I think the recurrence is just a reformulation of iterating over the individual bits. – Martin Ender – 2015-11-30T10:11:52.983

3I'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 – 2015-11-30T10:58:58.153

1@orlp: Well, that's a bummer. I'm kinda convinced now that your bonus is impossible. – El'endia Starman – 2015-11-30T20:18:25.387

@El'endiaStarman I've almost got it, I think. – Conor O'Brien – 2015-12-03T18:41:25.440

5

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

Conor O'Brien

Posted 2015-11-29T18:34:42.417

Reputation: 36 228

4Crossed out 7 still looks like a 7. – a spaghetto – 2015-11-29T21:40:42.583

2@quartata Not as bad as a crossed out 4. – orlp – 2015-11-29T21:51:08.227

5

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.

NinjaBearMonkey

Posted 2015-11-29T18:34:42.417

Reputation: 9 925

4

TeaScript, 9 bytes 11

TeaScript is Javascript for golfing

®x÷v¤)**2

Will golf more once I get back to my computer

Try it online!

Test all

Downgoat

Posted 2015-11-29T18:34:42.417

Reputation: 27 116

Does the interpreter understand any encodings other than UTF8? Using UTF8 encoding, I think your entry is 12 bytes long.

– Digital Trauma – 2015-11-30T20:37:07.097

4

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.

Dennis

Posted 2015-11-29T18:34:42.417

Reputation: 196 637

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 – 2017-04-01T19:38:25.827

4

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

Mego

Posted 2015-11-29T18:34:42.417

Reputation: 32 998

Nice job matching Jolf! – Conor O'Brien – 2015-11-29T21:28:25.317

+1 for having your interpreter accept CP437 encoding (or at least the hex representation of it) – Digital Trauma – 2015-11-30T20:49:06.513

2

JavaScript, 64 63 56 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

nicael

Posted 2015-11-29T18:34:42.417

Reputation: 4 585

instead of parseInt( you can do +("0b"+ – Downgoat – 2015-11-29T18:45:52.390

@Downgoat hm, it doesn't appear to give correct results. – nicael – 2015-11-29T18:48:04.070

[...n.toString(2)] and .join\`` – Conor O'Brien – 2015-11-29T18:48:12.530

1Even shorter w/ ES7 (49 bytes): n=>+("0b"+[...n.toString(2)].reverse().join\`)**2`. Doesn't work in any browsers yet – Downgoat – 2015-11-29T19:08:07.200

1@CᴏɴᴏʀO'Bʀɪᴇɴ Thanks, this saves some bytes. – nicael – 2015-11-29T19:45:47.167

This works for me in the latest version of Firefox: n=>(y=+('0b'+[...n.toString(2)].reverse().join``))*y (51 bytes) Or with exponentiation, 49 bytes:n=>+('0b'+[...n.toString(2)].reverse().join``)**2 but this doesn't work yet. – ETHproductions – 2015-11-29T20:48:28.513

@Eth In Safari it doesn't work, gonna try in Chrome. – nicael – 2015-11-29T20:51:45.310

@Eth With Chrome, the first example (51 bytes) doesn't work, but the second does. Those don't seem to be universal anyway. – nicael – 2015-11-29T20:58:58.100

2

CJam, 10 bytes

ri2bW%2b_*

Try it online

Reto Koradi

Posted 2015-11-29T18:34:42.417

Reputation: 4 870

2

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

Brad Gilbert b2gills

Posted 2015-11-29T18:34:42.417

Reputation: 12 713

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
$ 

Digital Trauma

Posted 2015-11-29T18:34:42.417

Reputation: 64 644

2

PHP, 45 bytes

echo pow(bindec(strrev(decbin($argv[1]))),2);

undefined

Posted 2015-11-29T18:34:42.417

Reputation: 211

1

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

pizzapants184

Posted 2015-11-29T18:34:42.417

Reputation: 3 174

1

Pyth - 9 bytes

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

^i_jQK2KK

Test Suite.

Maltysen

Posted 2015-11-29T18:34:42.417

Reputation: 25 023

1

, 12 chars / 21 bytes

⦅`ᶀ`+ᴙ(ïß2)²

Try it here (Firefox only).

Noncompetitive answer, 9 chars / 18 bytes

⦅Յ+ᴙ(ïⓑ)²

Try it here (Firefox only).

Mama Fun Roll

Posted 2015-11-29T18:34:42.417

Reputation: 7 234

1

Via this byte counter, gives 15 bytes (uses another encoding).

– nicael – 2015-11-29T23:07:47.870

I grade using UTF-8 (until I can get Mines encoding to work). – Mama Fun Roll – 2015-11-29T23:12:59.520

The... name of the language... is boxes? – corsiKa – 2015-11-30T21:45:22.947

It's ESMin in doublestruck. The Unicode chars aren't fully supported. – Mama Fun Roll – 2015-11-30T23:41:20.827

1

Pyth, 9 bytes

^i_.BQ2 2

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

TanMath

Posted 2015-11-29T18:34:42.417

Reputation: 1 431

1

Ruby, 35 bytes

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

Harsh Gupta

Posted 2015-11-29T18:34:42.417

Reputation: 131