Sum of Powers of 2

31

3

The Challenge

Given an integer input x where 1 <= x <= 255, return the results of powers of two that when summed give x.

Examples

Given the input:

86

Your program should output:

64 16 4 2

Input:

240

Output:

128 64 32 16

Input:

1

Output:

1

Input:

64

Output:

64

The output may contain zeros if the certain power of two is not present in the sum.

For example, input 65 may output 0 64 0 0 0 0 0 1.

Scoring

This is , so the shortest answer in each language wins.

SpookyGengar

Posted 2019-01-28T20:29:48.713

Reputation: 1 617

5Does the list have to be sorted highest to lowest? – Adám – 2019-01-28T20:56:31.180

2May we output some redundant zeros? – Jonathan Allan – 2019-01-28T20:58:32.633

@Adám going to say yes this time. I want the output to be somewhat similar to the binary representation of the number. ie 65 = 0 + 2^6 +0 +0 +0 +0 + 0 +2^0 – SpookyGengar – 2019-01-28T21:27:05.393

@JonathanAllan yes only if the zeros are present in the list in the same way that certain powers of two may not be present in the sum. For example, 65 may output 0 64 0 0 0 0 0 1 since those powers of two are not present in the sum. – SpookyGengar – 2019-01-28T21:28:46.090

4RE: "sorted highest to lowest" why add a restriction that was not part of the challenge and invalidates most existing answers? (Also what about little-endian?!) + it invalidates my Python answer since sets do not have any order. – Jonathan Allan – 2019-01-28T21:38:44.927

@JonathanAllan it was always part of the problem based on the output I provided, but I added that restriction explicitly after your question as I realized some may have been confused. – SpookyGengar – 2019-01-28T22:18:43.200

1As it was written it said "Given an integer input x where 1 <= x <= 255, return the results of powers of two that when summed give x.". Note that it is a common misconception that test cases are to help define a challenge. – Jonathan Allan – 2019-01-28T22:23:25.567

5@JonathanAllan I've removed the restriction. I'll keep that in mind next time I post another question - I'm still fairly new to this. :) – SpookyGengar – 2019-01-28T22:28:56.827

6I think you might want to state that any power of two may only be used once. Otherwise somebody could output "1 1 1" for the input 3. – Black Owl Kai – 2019-01-29T10:58:56.023

Can the output be separated by newlines instead of spaces? – Reinstate Monica -- notmaynard – 2019-01-29T23:48:27.330

@SpookyGengar: you should probably say explicitly in the question that the output can be in any order. I assumed from the test-case valid outputs that it had to be MSB to LSB, and only saw your comment while checking if an answer that isolated the lowest bit with n&-n was legal. – Peter Cordes – 2019-01-30T04:49:42.747

Is a leading zero in the output okay? i.e. 86[0, 64, 16, 4, 2] – Oliver – 2019-01-30T20:17:53.030

Answers

38

JavaScript (ES6), 28 bytes

f=n=>n?[...f(n&~-n),n&-n]:[]

Try it online!

Arnauld

Posted 2019-01-28T20:29:48.713

Reputation: 111 334

9You're the only person in the whole world who can make me upvote JavaScript answers! – sergiol – 2019-01-29T00:05:48.177

4@sergiol, why wouldn't you normally upvote a JS solution? A good solution is a good solution regardless of the language used or who posted it. – Shaggy – 2019-01-29T13:23:18.430

@Shaggy Because Arnauld seems the only person to do such Javascript solutions. His answers are pure genius! – sergiol – 2019-01-29T15:11:53.290

3@sergiol Thanks for the compliment, but that's not quite true. I'm regularly outgolfed by more clever answers -- and that's what this site is all about. ^^ – Arnauld – 2019-01-29T15:18:27.603

@Oliver I'm not sure. It seems like leading zeros (before 128) are forbidden. Otherwise, another possible variant is f=n=>n&&f(n&~-n)+[,n&-n]. – Arnauld – 2019-01-29T19:47:45.197

Nice alternative. Although there was no mention of leading zeros, the OP did allow zeros in the output. – Oliver – 2019-01-29T19:57:25.803

12

Jelly, 4 bytes

-2 since we may output zeros in place of unused powers of 2 :)

Ḷ2*&

Try it online!

How?

Ḷ2*& - Link: integer, n         e.g. 10
Ḷ    - lowered range of n            [  0,  1,  2,  3,  4,  5,  6,  7,  8,  9]
 2*  - two to the power of           [  1,  2,  4,  8, 16, 32, 64,128,256,512]
   & - bit-wise and                  [  0,  2,  0,  8,  0,  0,  0,  0,  0,  0]

Jonathan Allan

Posted 2019-01-28T20:29:48.713

Reputation: 67 804

12

Pure Bash, 20

echo $[2**{7..0}&$1]

Try it online!

Explanation

          {7..0}     # Brace expansion: 7 6 5 4 3 2 1 0
       2**{7..0}     # Brace expansion: 128 64 32 16 8 4 2 1
       2**{7..0}&$1  # Brace expansion: 128&n 64&n 32&n 16&n 8&n 4&n 2&n 1&n (Bitwise AND)
     $[2**{7..0}&$1] # Arithmetic expansion
echo $[2**{7..0}&$1] # and output

Digital Trauma

Posted 2019-01-28T20:29:48.713

Reputation: 64 644

11

Jelly, 6 bytes

BUT’2*

Try it online!

Explanation

BUT here is an explanation (note: I had assumed that we may only output the powers of 2 themselves and nothing else):

BUT’2* – Monadic link. Takes a number N as input. Example: 86
B      – Convert N to binary.                              [1, 0, 1, 0, 1, 1, 0]
 U     – Reverse.                                          [0, 1, 1, 0, 1, 0, 1]
  T    – Truthy indices.                                   [2, 3, 5, 7]
   ’   – Decrement.                                        [1, 2, 4, 6]
    2* – Raise 2 to that power.                            [2, 4, 16, 64]

"Proof" that it works correctly. The standard representation of an integer \$ X\$ in base 2 is a list \$\{x_1, x_2, x_3,\cdots, x_n\}\$, where \$x_i\in\{0,1\},\:\forall\:\: i\in\overline{1,n}\$, such that: $$X=\sum_{i=1}^n x_i\cdot 2^{n-i}$$ The indices \$i\$ such that \$x_i=0\$ obviously have no contribution so we're only interested in finding those such that \$x_i=1\$. Since subtracting \$i\$ from \$n\$ is not convenient (the powers of two all have exponents of the form \$n-i\$, where \$i\$ is any index of a \$1\$), instead of finding the truthy indices in this list we reverse it and then find them "backwards" with UT. Now that we've found the correct indices all we have to do is raise \$2\$ to those powers.

Mr. Xcoder

Posted 2019-01-28T20:29:48.713

Reputation: 39 774

1"ASCII-only" Sneaky there... – Erik the Outgolfer – 2019-01-28T21:05:16.470

1@EriktheOutgolfer I guess BUT2*H would work though. – Mr. Xcoder – 2019-01-28T21:08:30.643

1Pretty impressive that this works with an input of 302231454903657293676544. – Michael Karas – 2019-02-03T13:47:37.083

9

Python, 35 bytes

lambda n:[n&2**i for i in range(8)]

Little-endian with zeros at unused powers of 2.

Try it online!

Jonathan Allan

Posted 2019-01-28T20:29:48.713

Reputation: 67 804

8

APL (Dyalog Extended), 7 bytesSBCS

Anonymous tacit prefix function. Requires 0-based indexing (⎕IO←0).

2*⍸⍢⌽⍤⊤

Try it online!

2 two
* raised to the power of
 the ɩndices where true
 while
 reversed
 of
 the binary representation

Adám

Posted 2019-01-28T20:29:48.713

Reputation: 37 779

8

Catholicon, 3 bytes

ṫĊŻ

Try it online!

Explanation:

ṫ       Decompose         into the largest values where:
 Ċ               the input
  Ż       the bit count is truthy (equal to one)

Okx

Posted 2019-01-28T20:29:48.713

Reputation: 15 025

Interesting! Get TIO'd :D – Jonathan Allan – 2019-01-28T22:25:30.480

Works with 302231454903657293676544. Nice. – Michael Karas – 2019-02-03T13:54:40.963

8

Sledgehammer 0.2, 3 bytes

⡔⡸⢣

Decompresses into {intLiteral[2],call[NumberExpand,2]}.

Sledgehammer is a compressor for Wolfram Language code using Braille as a code page. The actual size of the above is 2.75 bytes, but due to current rules on meta, padding to the nearest byte is counted in code size.

lirtosiast

Posted 2019-01-28T20:29:48.713

Reputation: 20 331

2Huh! Neat little language, and all the characters are actually printable. – LegionMammal978 – 2019-01-29T15:41:30.590

And now I can't get the Peter Gabriel song out of my mind...

– Digital Trauma – 2019-01-31T22:14:52.030

8

05AB1E, 3 bytes

Ýo&

Port of @JonathanAllan's Jelly answer, so make sure to upvote him!

Contains zeros (including -loads of- trailing zeros).

Try it online or verify all test cases.

Explanation:

Ý      # Create a list in the range [0, (implicit) input]
       #  i.e. 15 → [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
       #  i.e. 16 → [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
 o     # Take 2 to the power of each value
       #  → [1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768]
       #  → [1,2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768,65536]
  &    # Bitwise-AND each value with the (implicit) input
       # 15 → [1,2,4,8,0,0,0,0,0,0,0,0,0,0,0,0]
       # 16 → [0,0,0,0,16,0,0,0,0,0,0,0,0,0,0,0,0]
       # (and output the result implicitly)

Kevin Cruijssen

Posted 2019-01-28T20:29:48.713

Reputation: 67 575

1... what?! Never honestly seen bitwise and used in osabie. Nice one. – Magic Octopus Urn – 2019-01-29T15:40:06.240

@MagicOctopusUrn I indeed also don't use it very often. Can't even find any other answer I've used & in. xD I have used Bitwise-XOR a couple of times, like here or here and Bitwise-NOT once here (which I later removed again after golfing further..). I do use Bitwise-AND, XOR, OR, NOT, SHIFT, etc. pretty often in Java, but in 05AB1E not so much. :)

– Kevin Cruijssen – 2019-01-29T15:55:23.303

7

Wolfram Language (Mathematica), 17 bytes

#~NumberExpand~2&

Try it online!

Mathematica strikes again.

lirtosiast

Posted 2019-01-28T20:29:48.713

Reputation: 20 331

This also works with input of 302231454903657293676544. – Michael Karas – 2019-02-03T13:56:38.813

7

C# (Visual C# Interactive Compiler), 29 bytes

Contains 5 unprintable characters.

n=>"€@ ".Select(a=>a&n)

Explanation

//Lambda taking one parameter 'n'
n=>
//String with ASCII characters 128, 64, 32, 16, 8, 4, 2, and 1
"€@ "
//Iterate through all the chars of the above string and transform them to
.Select(a=>
//A bitwise AND operation between the integer value of the current char and the input value
a&n)

Try it online!

Embodiment of Ignorance

Posted 2019-01-28T20:29:48.713

Reputation: 7 014

But we need to get rid of zeros, like n=>new int[8].Select((j,i)=>1<<i&n).Where(i=>i!=0) The part before Where is five bytes shorter btw – polfosol ఠ_ఠ – 2019-01-29T08:49:01.663

@polfosol The output may contain zeros – Jo King – 2019-01-29T09:06:35.510

2@JoKing Still, n=>new int[8].Select((j,i)=>1<<i&n) is 35 bytes long and we won't need additional flags and text encodings. – polfosol ఠ_ఠ – 2019-01-29T13:02:43.343

1Using ascii characters 0-7 should be shorter, eg n=>"INSERT ASCII HERE".Select(a=>1<<a&n) But I'm on a mobile device that can't display or type unprintables, so I'll have to wait till I get home to update the answer – Embodiment of Ignorance – 2019-01-29T16:34:30.920

7

R, 27 23 bytes

bitwAnd(scan(),2^(7:0))

Try it online!

Unrolled code and explanation :

A = scan()         # get input number A from stdin
                   # e.g. A = 65

bitwAnd( A , 2^(7:0))  # bitwise AND between all powers of 2 : 2^7 ... 2^0 and A
                       # and implicitly print the result
                       # e.g. B = bitwAnd(65, c(128,64,32,16,8,4,2,1)) = c(0,64,0,0,0,0,0,1)
  • 4 bytes thanks to @Kirill L.

digEmAll

Posted 2019-01-28T20:29:48.713

Reputation: 4 599

123 bytes with bitwise and. – Kirill L. – 2019-01-29T09:53:58.713

@KirillL.: brilliant ! – digEmAll – 2019-01-29T13:16:59.700

6

C# (Visual C# Interactive Compiler), 38 bytes

x=>{for(int y=8;y-->0;Print(x&1<<y));}

Try it online!

dana

Posted 2019-01-28T20:29:48.713

Reputation: 2 541

aw, close :P – ASCII-only – 2019-01-29T07:45:26.930

1Fails for inputs 1, 2, 4, 8, 16, etc. (the x>y should be x>=y instead). – Kevin Cruijssen – 2019-01-29T09:37:06.167

1

@ASCIIOnly - I'm telling you, the range operator is going to be sweet :)

– dana – 2019-01-29T13:43:13.873

@ASCII-only Mean while, you can use the flag /u:System.Linq.Enumerable and try this for 31 bytes

– Embodiment of Ignorance – 2019-01-29T23:18:52.453

@EmbodimentofIgnorance sure. but i'd prefer not to list language as "C# /u:System.Linq.Enumerable" :P – ASCII-only – 2019-01-30T04:54:39.297

5

C (clang), 133 110 63 58 bytes

58-byte solution thanks to @ceilingcat.

x=256;main(y){for(scanf("%d",&y);x/=2;)printf("%d ",y&x);}

Try it online!

a stone arachnid

Posted 2019-01-28T20:29:48.713

Reputation: 1 053

In C89, you can declare like main(){} and the return type defaults to int. Same for variables at global scope. Also, at least on normal implementations like clang, printf and scanf work without prototypes. You get warnings of course, but it's still valid C89 (maybe) or at least K&R C for them to be implicitly declared. The types of the C objects you pass as args defines how they're passed, so a char* and int* will Just Work without truncating pointers to 32-bit on x86-64 or anything. (Default argument promotions happen, same as for variadic functions which they are anyway.) – Peter Cordes – 2019-01-30T03:46:43.143

Or is this aiming to be valid C11 with no undefined behaviour? If so, proudly proclaim it. :) And BTW, writing a function that takes an output array as an arg would probably be smaller. Anyway, see Tips for golfing in C

– Peter Cordes – 2019-01-30T03:48:47.140

You can use bitwise & to check if a bit is set. Like y&(1<<x)&&printf("%d ",1<<x);. Or to not skip zeros, just printf("%d ", y&(1<<x)). Or instead of counting bit positions, use x=256 and x>>=1 to shift the mask. main(y){int x=256;for(scanf("%d",&y);x>>=1;)printf("%d ",y&x);} 63 bytes Try it online! clang will even compile that with -std=c11

– Peter Cordes – 2019-01-30T04:11:13.520

44 bytes – ceilingcat – 2019-02-09T01:25:57.310

5

05AB1E, 7 bytes

2вRƶ<oò

explanation:

2в        convert input to binary array
R         reverse array
ƶ<        multiply each item by it's index and subtract 1
oò        2^item then round down

Try it online!

Jackson

Posted 2019-01-28T20:29:48.713

Reputation: 101

Also works with input of 302231454903657293676544 – Michael Karas – 2019-02-03T14:00:35.210

5

C (gcc), 39 bytes

f(n){for(;n;n&=n-1)printf("%d ",n&-n);}

Try it online!

nwellnhof

Posted 2019-01-28T20:29:48.713

Reputation: 10 037

5

Haskell, 29 bytes

(mapM(\n->[0,2^n])[7,6..0]!!)

Try it online!

xnor

Posted 2019-01-28T20:29:48.713

Reputation: 115 687

5

Ruby, 25 bytes

->n{8.times{|i|p n&2**i}}

Try it online!

Reinstate Monica -- notmaynard

Posted 2019-01-28T20:29:48.713

Reputation: 1 053

4

Japt, 8 5 bytes

Æ&2pX

Try it

Æ&2pX     :Implicit input of integer U
Æ         :Map each X in the range [0,U)
 &        :  Bitwise AND of U with
  2pX     :  2 to the power of X

Alternative

Suggested by Oliver to avoid the 0s in the output using the -mf flag.

N&2pU

Try it

N&2pU     :Implicitly map each U in the range [0,input)
N         :The (singleton) array of inputs
 &        :Bitwise AND with
  2pX     :2 to the power of U
          :Implicitly filter and output

Shaggy

Posted 2019-01-28T20:29:48.713

Reputation: 24 623

1

Nice one. You can do N&2pU with -mf to avoid the 0s

– Oliver – 2019-01-29T02:54:19.913

4

Perl 6, 16 12 bytes

-4 bytes thanks to Jonathan Allan

*+&2**all ^8

Try it online!

Returns an All Junction with 8 elements. This is a rather non-standard way of returning, but generally, Junctions can act as ordered (at least until autothreading is implemented) lists and it is possible to extract the values from one.

Explanation:

*+&              # Bitwise AND the input with
   2**           # 2 raised to the power of
      all ^8     # All of the range 0 to 7

Jo King

Posted 2019-01-28T20:29:48.713

Reputation: 38 234

4

MATL, 5 bytes

BPfqW

Try it online!

Explanation

Consider input 86 as an example.

B    % Implicit input. Convert to binary (highest to lowest digits)
     % STACK: [1 0 1 0 1 1 0]
P    % Flip
     % STACK: [0 1 1 0 1 0 1]
f    % Find: indices of nonzeros (1-based)
     % STACK: [2 3 5 7]
q    % Subtract 1, element-wise
     % STACK: [1 2 4 6]
W    % Exponential with base 2, element-wise. Implicit display
     % STACK: [2 4 16 64]

Luis Mendo

Posted 2019-01-28T20:29:48.713

Reputation: 87 464

4

05AB1E, 9 bytes

Ýoʒ›}æʒOQ

Try it online!


This is also correct for 6-bytes, but it doesn't complete in time on TIO for 86:

05AB1E, 6 bytes

ÝoæʒOQ

Try it online!

Magic Octopus Urn

Posted 2019-01-28T20:29:48.713

Reputation: 19 422

1Both your answers output an empty set for 15, instead of [1,2,4,8] – Kevin Cruijssen – 2019-01-29T07:14:38.603

1@KevinCruijssen needed 2**0, nice catch. Ý over L. – Magic Octopus Urn – 2019-01-29T15:29:46.540

1Ah, I know the feeling. Also had L instead of Ý at first in my answer. – Kevin Cruijssen – 2019-01-29T15:31:18.720

4

Julia 0.6, 13 bytes

n->n&2.^(0:7)

Try it online!

Kirill L.

Posted 2019-01-28T20:29:48.713

Reputation: 6 693

4

TSQL, 43 39 bytes

Can't find a shorter fancy solution, so here is a standard loop. -4 bytes thanks to MickyT and KirillL

DECLARE @y int=255

,@ int=128s:PRINT @y&@ SET @/=2IF @>0GOTO s

Try it out

t-clausen.dk

Posted 2019-01-28T20:29:48.713

Reputation: 2 874

using the bitwise and (&) you can save a few with the following ,@ int=128s:print @y&@ set @/=2IF @>0GOTO s. This is hinted by @KirillL for the R answer – MickyT – 2019-01-31T19:49:48.453

@MickyT that worked like a charm. Thanks a lot – t-clausen.dk – 2019-02-01T00:02:02.523

4

K (oK), 19 16 bytes

-3 bytes thanks to ngn!

{*/x#2}'&|(8#2)\

Try it online!

oK does not have power operator, that's why I need a helper function {*/x#2} (copy 2 x times and reduce the resulting list by multiplication)

Galen Ivanov

Posted 2019-01-28T20:29:48.713

Reputation: 13 815

you can omit the { x}

– ngn – 2019-01-31T12:49:50.347

@ngn Thanks! I tried it and it worked, but I wasn't sure it is acceptible. – Galen Ivanov – 2019-01-31T15:25:02.337

4

CJam, 12 bytes

{:T{2\#T&}%}

Try it online!

Esolanging Fruit

Posted 2019-01-28T20:29:48.713

Reputation: 13 542

4

PHP, 41 39 bytes

for($c=256;$c>>=1;)echo$argv[1]&$c,' ';

Try it online!

Or 38 with no fun >>= operator and PHP 5.6+:

for($x=8;$x--;)echo$argv[1]&2**$x,' ';

Or 36 with little-endian ("0 2 4 0 16 0 64 0") output:

while($x<8)echo$argv[1]&2**$x++,' ';

Really I just wanted to use the >>= operator, so I'm sticking with the 39.

Tests:

$php pow2.php 86
0 64 0 16 0 4 2 0

$php pow2.php 240
128 64 32 16 0 0 0 0

$php pow2.php 1
0 0 0 0 0 0 0 1

$php pow2.php 64
0 64 0 0 0 0 0 0

$php pow2.php 65
0 64 0 0 0 0 0 1

640KB

Posted 2019-01-28T20:29:48.713

Reputation: 7 149

4

Alchemist, 125 bytes

_->In_x+128a+m
m+x+a->m+b
m+0x+a->n+a
m+0a->o+Out_b+Out_" "
n+b->n+x+c
n+0b+a->n+c
n+0a->p
o+b->o+c
o+0b->p
p+2c->p+a
p+0c->m

Try it online! or Test every input!

Explanation

_->In_x+128a+m           # Initialize universe with input, 128a (value to compare to) and m (state)
m+x+a->m+b               # If c has been halved, subtract min(a, x) from a and x and put its value into b
m+0x+a->n+a              # If x < a, continue to state n
m+0a->o+Out_b+Out_" "    # Else print and continue to state o
n+b->n+x+c               # Add min(a, x) (i.e. x) back to x, and add it to c (we're collecting a back into c)
n+0b+a->n+c              # Then, add the rest of a to c
n+0a->p                  # Then, go to state p
o+b->o+c                 # Add min(a, x) (i.e. a) to c - x _is_ greater than a and so contains it in its binary representation, so we're not adding back to x
o+0b->p                  # Then, go to state p
p+2c->p+a                # Halve c into a
p+0c->m                  # Then go to state m

ASCII-only

Posted 2019-01-28T20:29:48.713

Reputation: 4 687

3

Python 2, 43 40 bytes

f=lambda n,p=1:n/p*[1]and f(n,p*2)+[p&n]

Try it online!

ovs

Posted 2019-01-28T20:29:48.713

Reputation: 21 408

1@JonathanAllan this definitely helped. Thanks for notifying me. – ovs – 2019-01-28T22:20:46.993

1...and the restriction has been lifted, so -1 byte :) – Jonathan Allan – 2019-01-28T22:35:11.240

3

PowerShell, 45 37 bytes

param($a)7..0|%{1-shl$_}|?{$_-band$a}

Try it online!

Takes input $a, loops from 7 to 0, each iteration performing a bit-shift left (-shl) to formulate the powers-of-two for each exponent. We then pull out those ? (where) the number $_ shares a value -binaryand with the input number.

-8 bytes thanks to mazzy

AdmBorkBork

Posted 2019-01-28T20:29:48.713

Reputation: 41 581

1-shl$_ instead '2*'*$_+'1'|iex? – mazzy – 2019-01-29T03:54:45.160

@mazzy Oh, good call. I forgot we're dealing with numbers that work with -shl. – AdmBorkBork – 2019-01-29T13:03:11.137

3

C# (Visual C# Interactive Compiler), 33 bytes

n=>{for(;n>0;n&=n-1)Print(n&-n);}

Port of @Arnauld's JavaScript (ES6) answer, so make sure to upvote him!

Try it online.

Explanation:

n=>{            // Method with integer parameter and no return-type
  for(;n>0      //  Continue looping as long as `n` is larger than 0:
      ;         //    After every iteration:
       n&=n-1)  //     Bitwise-AND `n` by `n-1`
    Print(      //   Print with trailing newline:
      n&-n);}   //    `n` bitwise-AND `-n`

Kevin Cruijssen

Posted 2019-01-28T20:29:48.713

Reputation: 67 575

3

Java 8, 46 bytes

n->{for(;n>0;n&=n-1)System.out.println(n&-n);}

Try it online.

Port of @Arnauld's JavaScript (ES6) answer, so make sure to upvote him!

Explanation:

n->{                     // Method with integer parameter and no return-type
  for(;n>0               //  Continue looping as long as `n` is larger than 0:
      ;                  //    After every iteration:
       n&=n-1)           //     Bitwise-AND `n` by `n-1`
    System.out.println(  //   Print with trailing newline:
      n&-n);}            //    `n` bitwise-AND `-n`

Kevin Cruijssen

Posted 2019-01-28T20:29:48.713

Reputation: 67 575

Breakthrough in Java: 36 chars, by using this rule. Let's go back 5 years and golf all Java answers ever produced!

– Olivier Grégoire – 2019-01-29T16:29:55.570

@OlivierGrégoire Hmm, although I agree that it's most likely allowed, I'll pass tbh. I have used that rule when the input is for example an array, and we modify the input-array instead of returning a new one to save bytes. But adding an additional empty List argument just to store the output in to save byte with .add instead of System.out.println seems a bit cheaty imho. – Kevin Cruijssen – 2019-01-29T17:13:14.197

Kind of like how Array.sort() doesn't actually return anything, it just modifies the input. That seems legit. In C# you can use void f(out int x) or void f(ref int x) to return the result, but that doesn't seem to help w/ golf in my experiments. – dana – 2019-02-01T09:17:19.880

3

Perl 5, 22 bytes

say"@F"&2**$_ for 0..7

if newlines allowed as delimiter

22 bytes

28 bytes

Nahuel Fouilleul

Posted 2019-01-28T20:29:48.713

Reputation: 5 582

3

Python 2, 36 bytes

def f(x):n=1;exec'print n&x;n*=2;'*8

Try it online!

mdahmoune

Posted 2019-01-28T20:29:48.713

Reputation: 2 605

3

QBasic, 62 60 bytes

INPUT n
t=2^n
WHILE n
IF t<=n THEN
?t
n=n-t
ENDIF
t=t/2
WEND

Here's a REPL, slightly expanded to not break QB.js's compiler...

How does it work?

INPUT n     gets the input
t=2^n       sets t to a power of 2, overshooting the first power of two
WHILE n     while we haven't fully decnstucted the input
IF t<=n THEN        if we found a power of two that is in this number
?t          the print it
n=n-t           and 'deconstruct' n by that amount
ENDIF
t=t/2       drop down to the next power of two and
WEND        repeat testing

Edit Saved 2 bytes, while n>0 is equivalent to while n.

steenbergh

Posted 2019-01-28T20:29:48.713

Reputation: 7 772

3

APL(NARS) 18 chars, 36 bytes

{(⍵⊤⍨8⍴2)/⌽1,2*⍳7}

test:

  f←{(⍵⊤⍨8⍴2)/⌽1,2*⍳7}
  f 86
64 16 4 2 
  f 240
128 64 32 16 
  f 1
1 
  f 64
64 
  f 3
2 1 

RosLuP

Posted 2019-01-28T20:29:48.713

Reputation: 3 036

3

JavaScript - 33 bytes

n=>[..."01234567"].map(i=>n&2**i)

32 bytes, Oliver's suggestion

n=>[...2**29+'4'].map(x=>n&2**x)

MattH

Posted 2019-01-28T20:29:48.713

Reputation: 171

1

This appears to be 33 bytes, not 30. You can save a byte with this.

– Oliver – 2019-01-29T15:59:59.997

3

SAS, 91 bytes

data;input n;length o $99;z=1;do while(n);if mod(n,2) then o=z||o;n=int(n/2);z+z;end;cards;

Input is entered on separate lines after the cards; statement, like so:

data;input n;length o $99;z=1;do while(n);if mod(n,2) then o=z||o;n=int(n/2);z+z;end;cards;
86
240
1
64

Outputs a dataset with a string representation of the binary values in the o variable enter image description here

Explanation:

data;
input n; /* Read a line of input */
length o $99; /* Output string (max of 99 characters) */
z=1; /* First power of 2 */
do while(n); /* While remainder is not 0 */
    if mod(n,2) then o=z||o; /* If current binary digit is 1, append power of two to start of output */
    n=int(n/2); /* Move to next binary digit */
    z+z; /* Double current power of two to get next power of two (add it to itself) */
end;
cards;
86
240
1

Josh Eller

Posted 2019-01-28T20:29:48.713

Reputation: 241

2

Wolfram Language 58 bytes

Flatten[2^#&/@(Position[Reverse@IntegerDigits[#,2],1]-1)]&

IntegerDigits[#,2] returns the binary representation of the input, #, as a list of 1's and 0's.

Reverse@ reverses that list.

(Position[...,1]-1) lists the positions of the 1's in the reversed list and decrements each position by 1.

2^#&/@ 2 is raised to the power of (position -1) for each integer in the list.

Flatten removes nested braces.

DavidC

Posted 2019-01-28T20:29:48.713

Reputation: 24 524

The sort-order restriction has been lifted (also you may have zeros in place of unused powers of 2 now, if that helps) – Jonathan Allan – 2019-01-28T22:44:12.037

@JonathanAllan, Thanks, it saves 6 bytes. There are no zeros generated by this approach. – DavidC – 2019-01-28T23:24:03.617

2

Alchemist, 116 bytes

_->In_a+c
0f+a+0d->d
0f+a+d->e
0f+g->c
0_+0f+0g+0a+0d->f
0f+0g+0a+d->Out_c+Out_" "+f
f+e->f+a
f+c->f+2g
f+0c+0e+a->a

Try it online!

Uses a different approach to the existing Alchemist answer. Instead of counting back from 128, we count upwards, which can then support any positive input.

Explanation:

_->In_a          # Get input number of a atoms
       +c        # And initialise the power of 2
0f+a+0d->d       # Divmod the input by 2
0f+a+d->e

0f+0g+0a+d->Out_c+Out_" "+f    # If there is a remainder, print the current power of 2
0_+0f+0g+0a+0d->f              # Otherwise, do nothing

f+e->f+a         # Reset the number to the division by 2
f+0c+0e+a->a     # While the number is not zero, restart the loop

f+c->f+2g        # And double the power of 2
0f+g->c

Jo King

Posted 2019-01-28T20:29:48.713

Reputation: 38 234

2

x86-64 machine code, 12 bytes

This is a function you can call with the x86-64 System V calling convention, with this signature:
void binary_placevalues_withzero(uint8_t out[8] /*rdi*/, uint8_t val /*sil*/); or
void binary_placevalues_withzero(uint64_t *out /*rdi*/, uint8_t val /*sil*/); as a quick hack for making the output something you can print as one hex number for all 8 bytes.

It isolates the place values in increasing order into the output array, producing a result like 80 00 00 00 00 00 00 01 for esi = 129.

We start with mask = 1, and left-shift the mask by 1 until it overflows an 8-bit register.

nasm -l listing
    25 address   code bytes    global binary_placevalues_withzero
    26                         binary_placevalues_withzero:
    27 00000020 B101               mov  cl,1
    28                         .loop:
    29 00000022 88C8               mov  al,cl
    30 00000024 21F0               and  eax, esi     ; al,sil would cost a REX prefix 
    31 00000026 AA                 stosb             ; *rdi++ = val & mask
    32 00000027 00C9               add  cl,cl        ; left-shift the mask
    33 00000029 73F7               jnc  .loop        ; until it shifts out
    34 0000002B C3                 ret

An alternate version that only writes non-zero entries (thus producing an output array of length __builtin_popcount(val)) is also 12 bytes. This needs val zero-extended into ESI to avoid test false positives, unlike the version that doesn't skip zeros.

void binary_placevalues(uint8_t out[8] /*rdi*/, unsigned val /*esi*/);

    11                         global binary_placevalues
    12                         binary_placevalues:
    13 00000010 B001               mov  al,1
    14                         .loop:
    15 00000012 85F0               test  eax, esi    ; ESI must have its high bits clear, so high garbage in EAX doesn't matter
    16 00000014 7401               jz   .skip
    17 00000016 AA                 stosb             ; store if the mask matches
    18                         .skip:
    19 00000017 00C0               add  al,al        ; left-shift the mask
    20 00000019 73F7               jnc  .loop
    21 0000001B C3                 ret
    22                         

As usual, ISA extensions that let us save instructions cost more code bytes: a BMI1 version is 14 bytes. (https://www.felixcloutier.com/x86/BLSI.html and https://www.felixcloutier.com/x86/BLSR.html). Very efficient, though: each of these BLSI/BLSR instructions is only 1 uop.

     1                         global binary_placevalues_bmi1
     2                         binary_placevalues_bmi1:
     3                         .loop:
     4 00000000 C4E278F3DE         blsi  eax, esi    ; bit lowest-set isolate:  n &-n
     5 00000005 AA                 stosb
     6 00000006 C4E248F3CE         blsr  esi, esi    ; bit lowest-set reset: (n-1) & n, and sets ZF according to the result.
     7 0000000B 75F3               jnz .loop
     8 0000000D C3                 ret

(If there was high garbage in ESI, this would keep going, storing 0 bytes when EAX held an isolated bit outside the low 8.)

If you wanted speed, with BMI2 pdep you'd use a 64-bit mask that deposited the low 8 bits at their corresponding position within each byte. 1 uop / 3 cycle latency on Haswell/Skylake, at the cost of a 10-byte instruction to create the mask. :P But slow on Ryzen.


I'm not sure this is optimal. I don't think manually implementing n & -n and so on with xor/sub/and and so on would be a win, though.

Peter Cordes

Posted 2019-01-28T20:29:48.713

Reputation: 2 810

1Hah! I wrote up a solution that did exactly that before I saw your answer. I pushed the results onto the stack, which was elegant, but meant I had to preserve and restore the return address (cost 2 bytes for push+pop) and also had to maintain a counter so the caller would know how many values to pop from the stack (cost 3 bytes for xor to zero + inc inside loop). Total was 20 bytes. That's about as good as it's going to get. All the instructions are 1 or 2 bytes. Might be able to shave off 2-4 bytes by taking a pointer to a pre-allocated buffer as an argument, like you did here. – Cody Gray – 2019-02-09T08:51:50.647

@CodyGray: heh, that's fun. If you pop the ret addr, jmp rsi is 2 bytes, same as push/ret. But unbalances the return-address predictor stack, so in practice more instructions is better in this case. I kind of glossed over returning a size for the versions that skip 0 elements. The caller could pass a pre-zeroed buffer and treat the result as an implicit-length array (which works for my array-arg way, but not so much on the stack. Well I guess you could push 0 / call. But yeah, I was glad to find a fixed-length version with zeros so I didn't have to justify that or popcnt. – Peter Cordes – 2019-02-09T08:59:52.640

1

Retina 0.8.2, 25 bytes

.+
$*
M!`(\G1|\1\1)*1
%`1

Try it online! Explanation:

.+
$*

Convert to unary.

M!`(\G1|\1\1)*1

Match as many powers of 2 as possible, and then an extra 1. This gives a total sum of the next power of 2. The regular expression is greedy (default), so tries to consume the largest possible power of 2 at each match. The M! then causes the matches themselves to be listed on separate lines.

%`1

Convert each line back to decimal.

Neil

Posted 2019-01-28T20:29:48.713

Reputation: 95 035

1

Charcoal, 12 bytes

I⮌E⮌↨N²×ιX²κ

Try it online! Link is to verbose version of code. Includes zero values (+2 bytes to remove). Explanation:

     N          Input number
    ↨           Converted to base (MSB first)
      ²         Literal 2
   ⮌            Reversed (i.e. LSB first)
  E             Map over bits
        ι       Current bit
       ×        Multiplied by
          ²     Literal 2
         X      Raised to power
           κ    Current index
 ⮌              Reversed (back to MSB first)
I               Cast to string
                Implicitly print on separate lines

Neil

Posted 2019-01-28T20:29:48.713

Reputation: 95 035

Apparently the restriction on output order has been removed, which means that the first can be removed for a 1-byte saving. – Neil – 2019-01-29T09:51:41.163

Nice. This also works with an input of 302231454903657293676544. – Michael Karas – 2019-02-03T13:53:20.797

1

Alchemist, 274 bytes

_->9a+In_x+s
s+a->s+b+c
s+x->s+y+z
s+0a+0x+b->b+d+m
s+0a+0x+0b->n+e
d+m->d+2n
d+0m->e
e+n->e+m
e+0n+b->d
e+0n+0b->h
h+m->h+u+v
h+0m->t
t+y+u->t
t+0y+u->f
t+y+0u->g+p
t+0y+0u->p
g+0p+z+v->g
g+0v->f
f+c->f+a
f+z->f+x
f+u->f
f+v->f
f+y->f
f+0v+0u+0z+0c+0y+a->s
p->Out_v+Out_" "

Try it online!

Ungolfed & Serialized

The algorithm is generating the powers of two from above, subtracting them from the input, check whether it's less or equal (output & decrement value in that case) or not and repeat while having enough copies of every value, to restore stuff (reading in Alchemist is pretty much destructive).

The "states" s0X can be merged, same with nxt without changing correctness of the program by combining all the zero-rules. The order of setting up copies or cleanup doesn't matter1:

_ -> 9a + In_x + s00

# Setup copies of x and a
s00 + a -> s00 + b + c
s00 + 0a -> s01
s01 + x -> s01 + y + z
s01 + 0x + b-> b+s1 + m
s01 + 0x +0b -> n+s2

# Compute power of
s1 +  m -> s1 + 2n
s1 + 0m -> s2

s2 +  n      -> s2 + m
s2 + 0n +  b -> s1
s2 + 0n + 0b -> s3

# Duplicate the power of two
s3 + m -> s3 + u+v
s3 +0m -> tst

# Check if it's below the value
tst +  y +  u -> tst
tst + 0y +  u -> nxt0                  # if not continue
tst +  y + 0u -> go + Out_v + Out_" "  # if not equal, output & continue
tst + 0y + 0u -> Out_v + Out_" "       # if equal, output

# Decrement the current value
go + z + v -> go
go + 0v -> nxt0

# Clear & restore for "next iteration"
nxt0 + c -> nxt0 + a  # restore counter
nxt0 + 0c->nxt1
nxt1 + z -> nxt1 + x  # restore current value (possibly decremented)
nxt1 + 0z -> nxt2
nxt2 + u -> nxt2      # clean up remainder of power of two ..
nxt2 + 0u -> nxt3
nxt3 + v -> nxt3      # .. and its copy
nxt3 + 0v -> nxt4
nxt4 + y -> nxt4      # clean up the rest of comparison
nxt4 + 0y + a -> s00

Try it online!

1: The way to read it is like this: The first atom on the left-handside encodes a state (to serialize control-flow), the other atoms are counters which are replaced by the right-handside.

ბიმო

Posted 2019-01-28T20:29:48.713

Reputation: 15 345

explanation pls – ASCII-only – 2019-01-29T01:49:06.650

@ASCII-only: Done :) – ბიმო – 2019-01-29T01:57:02.210

1btw pls compress debug output, i.e. rule 100 times -> [rule] x 100 – ASCII-only – 2019-01-29T02:19:38.437

argh i keep getting close (read: i'm terrible at this) – ASCII-only – 2019-01-29T02:35:06.053

1145? m = halve, n = compare, o = restore x, p = refill d. a = value to compare to, b = value to compare a with to restore x, c = value to refill d with – ASCII-only – 2019-01-29T02:38:11.517

also it would be nice to have better determinism detection, although it would probably be hard (better = counting rules that don't affect each other as deterministic) – ASCII-only – 2019-01-29T02:42:33.987

deterministic 145? – ASCII-only – 2019-01-29T02:44:20.827

granted, this takes advantage of the fact that max is 255 – ASCII-only – 2019-01-29T02:45:51.963

137? – ASCII-only – 2019-01-29T02:48:24.537

better state change. EDIT: actually, 131? – ASCII-only – 2019-01-29T03:12:40.480

128? can probably be golfed more – ASCII-only – 2019-01-29T03:16:58.263

Order doesn’t matter, idk if that helps – ASCII-only – 2019-01-29T03:40:46.777

Also wait they’re broken – ASCII-only – 2019-01-29T03:42:36.030

Yeah 137, fix for 128 makes it 138

– ASCII-only – 2019-01-29T03:49:46.330

I’m sure you can make yours deterministic the same way I did, chaining instead of merging clears and possibly restoring x every time you decrement from y – ASCII-only – 2019-01-29T04:00:01.553

@ASCII-only: That's a rather different algorithm (and way better golfed), probably you should post it as a separate answer. – ბიმო – 2019-01-31T14:59:39.717

134, still working on it, will post later – ASCII-only – 2019-02-01T00:24:21.043

1

Pari/GP, 31 bytes

n->[2^i|i<-[0..n],bittest(n,i)]

Try it online!

alephalpha

Posted 2019-01-28T20:29:48.713

Reputation: 23 988

1

MATL, 5 bytes

BXdXB

Try it online!

Explanation

B    % Convert to binary (as a vector)
Xd   % Give a diagonal matrix with the vector on its diagonal
XB   % Convert each row of the matrix to decimal

alephalpha

Posted 2019-01-28T20:29:48.713

Reputation: 23 988

Nice result with 302231454903657293676544 working. – Michael Karas – 2019-02-03T13:59:26.283

1

05AB1E, 6 bytes

bRεNo*

Try it online! or as Test Suite

Explanation

       # Implicit input n
b      # Convert to binary
 R     # Reverse
  ε    # For each digit d in the binary number
   N   # Push its index N
    o* # Compute d*2^N
       # Implicit output of list of results

Wisław

Posted 2019-01-28T20:29:48.713

Reputation: 554

1

F# (.NET Core), 41 bytes

fun x->Seq.map(fun y->x&&&pown 2 y)[0..7]

Try it online!

dana

Posted 2019-01-28T20:29:48.713

Reputation: 2 541

1

J, 13 bytes

(2^I.)&.|.@#:

Try it online!

Galen Ivanov

Posted 2019-01-28T20:29:48.713

Reputation: 13 815

1

Ruby, 26 bytes

->n{(0..7).map{|i|n&2**i}}

Try it online!

Same approach as Jonathan Allan's answer.

Kirill L.

Posted 2019-01-28T20:29:48.713

Reputation: 6 693

1

JS, 103 bytes

m=Math;f=a=>2**(m.floor(m.log2(a)));x=prompt()*1;y="";while(x>0&&x<256){z=f(x);y=y+" "+z;x=x-z}alert(y)

Nautilus

Posted 2019-01-28T20:29:48.713

Reputation: 221

1

ArnoldC, 609 bytes

IT'S SHOWTIME
HEY CHRISTMAS TREE N
YOU SET US UP 0
GET YOUR ASS TO MARS N
DO IT NOW
I WANT TO ASK YOU A BUNCH OF QUESTIONS AND I WANT TO HAVE THEM ANSWERED IMMEDIATELY
HEY CHRISTMAS TREE I
YOU SET US UP 128
HEY CHRISTMAS TREE B
YOU SET US UP 0
STICK AROUND I
GET TO THE CHOPPER B
HERE IS MY INVITATION I
LET OFF SOME STEAM BENNET N
ENOUGH TALK
BECAUSE I'M GOING TO SAY PLEASE B
BULLSHIT
TALK TO THE HAND I
GET TO THE CHOPPER N
HERE IS MY INVITATION N
GET DOWN I
ENOUGH TALK
YOU HAVE NO RESPECT FOR LOGIC
GET TO THE CHOPPER I
HERE IS MY INVITATION I
HE HAD TO SPLIT 2
ENOUGH TALK
CHILL
YOU HAVE BEEN TERMINATED

Try it online!

I apologise.

Sasha

Posted 2019-01-28T20:29:48.713

Reputation: 431

1

APL (Dyalog Extended), 6 bytes

2*⍸⌽⊤⎕

2 to the * power of the indices of the true bits of the reversed binary encoding of the input

Try it online!

Richard Park

Posted 2019-01-28T20:29:48.713

Reputation: 21

0

Chip -w, 115 bytes

H!ZZ--ZZZ--ZZZ--ZZZZ-Z-ZZZ-Z-ZZt
@^))e G>)e F>)e E>).d[DC].b[Bze
a,x]dc[(' b[('ca[L'`e'*sece'A]a
 H]--b['*fa['b^-['

Try it online!

Takes a single raw byte as input, and returns some mix of 128 64 32 16 8 4 2 1 and 000 00 00 00 0 0 0 0

In the TIO, the argument -wgNN will provide this program with a byte of value 0xNN. So, -wg5c provides 0x5c. The special value -wgkk will instead generate a random byte.

Chip is a 2D language where each element can interact with its four neighbors with single bit values only. An unsmooshed version of the above would look like this:

!ZZZ--ZZZ--ZZZ--ZZZ--ZZ--ZZ--ZZ--Zt
)))---))---))---))---)---)---)---)-e
|||H  ||G  ||F  ||E  |D  |C  |B  |A
xx)]d xx]d xx]d xx]d )]d x]d x]d x]d
xxx]c ))]c xx]c x)]c x]c )]c x]c x]c
x)x]b )x]b ))]b x)]b x]b x]b )]b x]b
)xx]a xx]a )x]a )x]a x]a x]a x]a )]a

s*f

Here we can see eight blocks, one for each power of two, from left to right. Each block contains a grid specifying which bits should be turned on for each character of that power. The input bits (capital letters) are connected as switches to control whether each digit should be its actual value, or zero.

Phlarx

Posted 2019-01-28T20:29:48.713

Reputation: 1 366

0

x86 Machine Code, 20 bytes

; ECX is the input value ('x')
; EDX is a temporary, used for manipulations of 'x'
; EAX is a counter, which will also be the return value
; EBP is a temporary holding space for the return address

           GetSumOfPowersOf2:
5D            pop    ebp              ; save return address
31 C0         xor    eax, eax         ; counter = 0

           MainLoop:
89 CA         mov    edx, ecx         ; \
F7 DA         neg    edx              ; | temp = (x & -x)
21 CA         and    edx, ecx         ; /
52            push   edx              ; push temp onto stack
40            inc    eax              ; increment counter
89 CA         mov    edx, ecx         ; \ 
4A            dec    edx              ; | x = (x & (x - 1))
21 D1         and    ecx, edx         ; /
75 F1         jne    SHORT MainLoop   ; loop while x != 0

55            push   ebp              ; restore return address
C3            ret                     ; return to return address, with result in EAX

These bytes define a function, which takes as input a single 32-bit integer argument in the ECX register (the choice of which register to pass the input in is rather arbitrary, but ECX is the one used in the __fastcall calling convention). This is the value x from the question.

x is assumed to be non-zero, since it is given that 1 <= x <= 255. This allows us to only test the loop condition at the bottom of the loop.

The bulk of the code is a big ol' loop that calculates the powers of two using binary bit-twiddling and pushes them onto the stack. On x86, the PUSH instruction pushes a register value onto the stack and requires only 1 byte to encode, so it's a natural choice. The caller of this function will then just retrieve the return values by POPing them off the stack. Although this is a non-standard convention (by convention, a function's result is either returned in a register or stored into a memory address via a pointer), it works.

Well, as long as you attend to one little detail: the fact that the CALL instruction pushes the return address onto the stack, and the fact that the RET instruction knows where to return by popping the return address pushed onto the stack by the CALL instruction. So, if we want to return values on the stack, we need to preserve the return address at the top of the function. This is done by POPing the value at the top of the stack into the EBP register for safe-keeping, PUSHing the return values onto the stack during the loop, and then PUSHing the value in EBP (the preserved return address) onto the stack at the position where the RET instruction will expect to find it.

With this arrangement, when control returns to the caller, all they'll have to do is POP off the return values. Of course, they need to know how many values to pop off the stack, so we have to maintain a counter inside of the loop. The EAX register was chosen for this counter, since in all x86 calling conventions, functions return their result in the EAX register. This function returns as its result the number of values to pop off of the stack.

The caller would do something like this to exercise the function:

    mov   ecx, 86             ; put input value ('x') into ECX for passing to function
    call  GetSumOfPowersOf2   ; call the function
    mov   ecx, eax            ; save the function's return value (number of values to pop off stack)
GetAndPrint:
    pop   eax                 ; pop value off of stack into EAX
    call  PrintValueInEAX     ; print the value stored in EAX
    dec   ecx                 ; decrement counter
    jnz   SHORT GetAndPrint   ; loop while counter != 0

Cody Gray

Posted 2019-01-28T20:29:48.713

Reputation: 2 639

0

Pushy, 9 bytes

oBL:K2*#.

Try it online!

oB         \ Push binary digits to stack (least significant bit at the top).
  L:       \ len(stack) times do:
    K2*    \     Multiply all items by 2
       #.  \     Pop and print the top item

FlipTack

Posted 2019-01-28T20:29:48.713

Reputation: 13 242