title: Sum of Powers of 2

text:
# Question
Title: Sum of Powers of 2
**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.

# Answer
> 42 votes
# JavaScript (ES6), 28 bytes

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

```

Try it online!

# Answer
> 15 votes
# 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]

```

# Answer
> 13 votes
# 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.

# Answer
> 13 votes
# 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

```

# Answer
> 12 votes
# 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!**

# Answer
> 10 votes
# Catholicon, 3 bytes

```
ṫĊŻ

```

Try it online!

Explanation:

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

```

# Answer
> 9 votes
# 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

# Answer
> 9 votes
# 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.

# Answer
> 8 votes
# 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)

```

# Answer
> 7 votes
# Wolfram Language (Mathematica), 17 bytes

```
#~NumberExpand~2&

```

Try it online!

Mathematica strikes again.

# Answer
> 7 votes
# 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!

# Answer
> 7 votes
# , ~~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.

# Answer
> 6 votes
# C# (Visual C# Interactive Compiler), 38 bytes

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

```

Try it online!

# Answer
> 6 votes
# C (gcc), 39 bytes

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

```

Try it online!

# Answer
> 5 votes
# 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

```

# Answer
> 5 votes
# 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!

# Answer
> 5 votes
# 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!

# Answer
> 5 votes
# Julia 0.6, 13 bytes

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

```

Try it online!

# Answer
> 5 votes
# Haskell, 29 bytes

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

```

Try it online!

# Answer
> 5 votes
# Ruby, 25 bytes

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

```

Try it online!

# Answer
> 5 votes
# 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!

# Answer
> 4 votes
# 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 `0`s 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

```

# Answer
> 4 votes
# 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]

```

# Answer
> 4 votes
# 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!

# Answer
> 4 votes
# 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**

# Answer
> 4 votes
# 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

```

# Answer
> 4 votes
# 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)

# Answer
> 4 votes
# CJam, 12 bytes

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

```

Try it online!

# Answer
> 4 votes
# 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

```

# Answer
> 4 votes
# 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

```

# Answer
> 4 votes
# Piet \+ ascii-piet, 88 bytes (4×22=88 codels)

*My first Piet answer!*

```
taqu ci?aqtqqiarufqqrNdsssec ?a??q??vejraimMdk??e lane???nv??rr ?Mddtqe ll esufnvsbiesue

```

In grid form:

```
taqu ci?aqtqqiarufqqrn
dsssec ?a??q??vejraimm
dk??e lane???nv??rr ?m
ddtqe ll esufnvsbiesue

```

As a PNG:
And with larger codels:

Try Piet online!

In my best attempt at pseudocode:

```
n=input+1
p=256
while p>=1
  {p=p/2
  if n>p
    {n=n-p
    print p}}

```

# Answer
> 3 votes
# Python 2, ~~43~~ 40 bytes

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

```

Try it online!

# Answer
> 3 votes
# 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 `-b`inary`and` with the input number.

*-8 bytes thanks to mazzy*

# Answer
> 3 votes
# 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`

```

# Answer
> 3 votes
# 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`

```

# Answer
> 3 votes
# Perl 5, 22 bytes

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

```

if newlines allowed as delimiter

22 bytes

28 bytes

# Answer
> 3 votes
# Python 2, 36 bytes

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

```

Try it online!

# Answer
> 3 votes
# 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 deconstucted the input
IF t<=n THEN        if we found a power of two that is in this number
?t          then 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`.

# Answer
> 3 votes
# JavaScript - 33 bytes

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

```

# 32 bytes, Oliver's suggestion

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

```

# Answer
> 3 votes
# 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

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

```

# Answer
> 2 votes
# 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.

# Answer
> 2 votes
# 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

```

# Answer
> 2 votes
# 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.

# Answer
> 2 votes
# Vyxal, 3 bytes

```
ʀE⋏

```

Try it Online!

```
ʀE⋏
ʀ    # Range from zero to the input number, inclusive
 E   # Calculate 2 to the power of each list item (vectorized)
  ⋏  # Bitwise AND each list element with the input number

```

# Answer
> 2 votes
# APL, 11 bytes

```
2*8-⍸⎕⊤⍨8⍴2

```

Explanation on example of number 86.

Input number: 86
`⊤⍨8⍴2` Convert to bits: 0 1 0 1 0 1 1 0
Indexes of ones: 2 4 6 7
`8-` Substract from eight: 6 4 2 1
`2*` Powers of two: 64 16 4 2

# Answer
> 1 votes
# 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.

# Answer
> 1 votes
# Charcoal, 12 bytes

```
Ｉ⮌Ｅ⮌↨Ｎ²×ιＸ²κ

```

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

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

```

# Answer
> 1 votes
# 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.

# Answer
> 1 votes
# Pari/GP, 31 bytes

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

```

Try it online!

# Answer
> 1 votes
# 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

```

# Answer
> 1 votes
# 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

```

# Answer
> 1 votes
# F# (.NET Core), 41 bytes

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

```

Try it online!

# Answer
> 1 votes
# , 13 bytes

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

```

Try it online!

# Answer
> 1 votes
# Ruby, 26 bytes

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

```

Try it online!

Same approach as Jonathan Allan's answer.

# Answer
> 1 votes
# 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)

```

# Answer
> 1 votes
# 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.

# Answer
> 1 votes
# Regex (Perl / PCRE2 / Boost / Python`regex`), ~~16~~ 13 bytes

```
x(x((?1))\2|)

```

Takes its input in unary, as the length of a string of `x`s. Returns its result as the list of matches (each is also a string of `x`s whose length is the value).

Try it online! \- Perl
Try it online! \- Perl (test cases only)
Try it online! \- PCRE2
Try it online! \- Boost
Try it online! \- Python `import regex`

This is a power of 2 regex that I came up with just for this challenge. It's possible that nobody has ever seen this before, and either way it will be useful in other challenges (so far, Number of binary partitions). It needs absolutely no context, and can capture a power of 2 anywhere within a unary string. It doesn't use any special feature other than non-atomic recursion and a standard backreference.

```
x            # match += 1
(            # Define subroutine (?1)
    x        # match += 1
    ((?1))   # \2 = match made by recursive call; match += \2
    \2       # match += \2
|    # or
             # Match nothing, causing a cascading pop to the top level of
             # recursion, ending the match.
)

```

Note that while `((?R))\1|x` (10 bytes) would theoretically greedily match powers of 2 with the same end result as the 13 byte regex presented above, regex engines throw an error instead of running it because the recursive path doesn't consume any characters before calling itself. Regex is designed to be guaranteed to halt in finite time, thus is given this rule much like the one where any loop with no upper limit on its iteration count will exit after making a zero-width match. So all the methods of matching powers of 2 using recursion or nested backreferences are stuck with using \\$1+2+4+...+1\\$ instead of \\$1\times 2\times 2\times 2\times...\\$

Also note that the non-atomic recursive regex presented above is not to be confused with the PCRE1 atomic recursive regex `^(x(?1)?x|x)$` (Try it online!), which can't be adapted to match the largest power of 2 that fits in the available space, because unless it matches exactly the entire string, it ends up matching seemingly arbitrary powers of 2. And to work on any other engine besides PCRE1, it must be modified, either as `^(x(?>(?1))?x|x)$` or `^x(x(?1)?+x|x)?$` to be explicitly atomic: Try it online!

# Regex (PCRE2 / Ruby), ~~17~~ 14 bytes

```
x(x(\g<1>)\2|)

```

Try it online! \- PCRE2
**Try it online! \- Ruby**

This is a straight port of the 13 byte recursive regex to Ruby's subroutine call syntax.

# Regex (Perl / PCRE / .NET), 16 bytes

```
x((?(1)\1\1|x))*

```

Try it online! \- Perl
**Try it online! \- PCRE1**
Try it online! \- PCRE2
**Try it online! \- .NET**

This power of 2 matching is based on the regex `^(\1\1|^x)*x$` (Try it online!), which uses nested backreferences. But since it must be able to start its match anywhere inside the input, it can't make use of the `^` anchor. A `(?(N)set|unset)` conditional is used instead, to ensure the first iteration is seeded only once.

```
      # tail = input number; no need to anchor, as all positive inputs match
x             # tail -= 1; head += 1
(
    (?(1)     # Only allow the second alternative to match on the first iteration,
              # when \1 is unset, and the first alternative to match on every
              # subsequent iteration.
        \1\1  # \1 *= 2; tail -= \1; head += \1
    |
        x     # \1 = 1; tail -= \1; head += \1
    )
)*            # Iterate the above as many times as possible, minimum 0
              # Return match = head

```

# Regex (Perl / Java / PCRE / .NET), 18 bytes

```
x(\1\1|(?!\2)x())*

```

Try it online! \- Perl
**Try it online! \- Java**
Try it online! \- PCRE1
Try it online! \- PCRE2
Try it online! \- .NET

This is a port of the Perl/PCRE/.NET version, to regex engines that lack conditionals. An empty capture `\3` is used to keep track of whether the loop has finished its first iteration.

```
            # tail = input number; no need to anchor, as all positive inputs match
x           # tail -= 1; head += 1
(
    \1\1    # This can only match on iterations other than the first, since \1 is
            # unset on the first iteration; \1 *= 2; tail -= \1; head += \1
|
    (?!\2)  # Only allow a match on the first iteration, when \2 is unset.
    x       # \1 = 1; tail -= \1; head += \1
    ()      # \2 = 0
)*          # Iterate the above as many times as possible, minimum 0
            # Return match = head

```

# Regex (.NET), 19 bytes

```
(x(x?)(?<2>\2\2)*)*

```

Takes its input in unary, as a string of `x` characters whose length represents the number. Returns its output as the list of captures on the Balancing Group `\1` stack, whose lengths represent the numbers.

Try it online!

```
(
    x         # \1 = 1
    (x?)      # \2 = 1 or 0; \1 += \2
    (?<2>     # Alias as capture group \2
        \2\2  # \2 = \2 * 2; \1 += \2
    )*        # Iterate the above as many times as possible, minimum zero
)*            # Iterate the above as many times as possible, minimum zero, on
              # each iteration pushing the capture onto the group \1 stack.

```

Unlike Calculate the prime factors, in this challenge, returning the output as a list of matches golfs better than pushing it onto the Balancing Group stack, even when we take advantage of .NET's ability to alias a capture group.

Without capture group aliasing, this golfs even worse. We can't use `(x((?(2)\2\2|x))*)*`, because when starting a new power of 2, `\2` is already set and the first iteration won't be seeded with `x`. And it's not just a simple matter of clearing the `\2` stack with a `(?<-2>)*`, because that attempts to loop a zero-width match and will stop after one iteration. So, patching this either results in the monstrosity `(x((?(2)\2\2(?<-2>)|x))*(?<-2>)?)*` (34 bytes): Try it online!, or, slightly better, `(x((?(3)\2\2|x()))*(?<-3>)?)*` (29 bytes): Try it online! This is in fact comparable to not even explicitly using Balancing Groups: `(x(?=(.*))((?(?=\2)x|\3\3))*)*` (30 bytes): Try it online!

# Regex (ECMAScript / Python or better), 27 bytes

```
(?=.*?(((x+)(?=\3$))*x$))\1

```

**Try it online! \- ECMAScript**
Try it online! \- Perl
Try it online! \- Java
Try it online! \- PCRE
Try it online! \- Boost
**Try it online! \- Python**
Try it online! \- Ruby
Try it online! \- .NET

In regex flavors that lack both nested and forward-declared backreferences, an entirely different method of matching powers of 2 must be used: `^((x+)(?=\3$))*x$` (Try it online!). This is dependent on ending exactly at the end of the string, so the capturing of the power of 2 is done inside a lookahead.

```
        # tail = input number; no need to anchor, as all positive inputs match
(?=
    .*?                  # Decrease tail by the minimum necessary to match:
    (                    # \1 = largest power of 2 less than or equal to tail
        (
            (x+)(?=\3$)  # Assert tail is even; tail /= 2
        )*               # Iterate the above as many times as possible, minimum 0
        x$               # Assert tail == 1
    )
)
\1                       # Return \1 as the match

```

# Regex (Perl / PCRE / Python`regex` / Ruby / .NET), 27 bytes

```
x((?=(\3)?)((?(2)\2\2|x)))*

```

Try it online! \- Perl
Try it online! \- PCRE1
Try it online! \- PCRE2
Try it online! \- Python `import regex`
Try it online! \- Ruby
Try it online! \- .NET

This is a port of the Perl/PCRE2/.NET version to regex engines lacking nested backreferences.

Although this version is of equal length to the ECMAScript one, it is of interest due to being much faster than it (and the recursive version) on regex engines that support it.

```
          # tail = input number; no need to anchor, as all positive inputs match
x                 # tail -= 1; head += 1
(
    (?=(\3)?)     # \2 = \3, or unset if \3 is unset
    (             # \3
        (?(2)     # Only allow the second alternative to match on the first
                  # iteration, when \2 is unset, and the first alternative to
                  # match on every subsequent iteration.
            \2\2  # \3 = \2 * 2; tail -= \3; head += \3
        |
            x     # \3 = 1; tail -= \3; head += \3
        )
    )
)*                # Iterate the above as many times as possible, minimum 0
                  # Return match = head

```

# Regex (Perl / Java / PCRE / Python`regex` / Ruby / .NET), 29 bytes

```
x((?=(\3)?)(\2\2|(?!\4)x()))*

```

Try it online! \- Perl
Try it online! \- Java
Try it online! \- PCRE1
Try it online! \- PCRE2
Try it online! \- Python `import regex`
Try it online! \- Ruby
Try it online! \- .NET

This is a combination of the no-nested-backreferences and no-conditionals ports, and again, the proviso applies about it being faster than the ECMAScript and recursive versions.

# Answer
> 1 votes
# K (ngn/k), 26 bytes

```
{_0.5+`exp x*`ln 2}'*|=|2\

```

Try it online!

My first function-less K answer. Port of Xcoder's Jelly answer.

Explanation:

```
{_0.5+`exp x*`ln 2}'*|=|2\      Main program.
                        2\      Convert to base 2
                       |        Reverse
                      =         Group into falsey and truthy indices
                    *|          Select the second element (i.e. truthy indices)
                   '            For each of them
{                 }             Execute a function that
      `exp x*`ln 2              Raise the argument to the power of 2
 _0.5+                          Then round it

```

# Answer
> 0 votes
# 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.

# Answer
> 0 votes
# 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 `POP`ing 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 `POP`ing the value at the top of the stack into the `EBP` register for safe-keeping, `PUSH`ing the return values onto the stack during the loop, and then `PUSH`ing 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

```

# Answer
> 0 votes
# 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

```

# Answer
> 0 votes
# Desmos, 55 bytes

```
f(n)=2^{b[mod(floor(n/2^b),2)=1]}
b=[0...floor(log_2n)]

```

Port of Mr. Xcoder's Jelly answer.

Try it on Desmos!

# Answer
> 0 votes
# Thunno 2, 4 bytes

```
LOÆ&

```

Attempt This Online!

Port of Jonathan Allan's Jelly answer.

#### Explanation

```
LOÆ&  # Implicit input  ->  10
L     # Lowered range   ->  [0,1,2,3,4,5,6,7,8,9]
 O    # Two power       ->  [1,2,4,8,16,32,64,128,256,512]
  Æ&  # Bitwise AND     ->  [0,2,0,8,0,0,0,0,0,0]
      # Implicit output

```

# Answer
> 0 votes
# Uiua, 9 bytes

```
ⁿ:2▽:⇡⧻.⋯

```

get the bit representation as a list

`⇡⧻.` make a list of the same length, counting up from 1 \[1, 2, ...\]

`▽:` keep the values from the incrementing list for which there is a truthy bit in the bit representation list

`ⁿ:2` 2^n

---
Tags: code-golf, binary
---


title: Situations when recursion helps

text:
# Question
Title: Situations when recursion helps
Recursion is actually quite powerful, sometimes its doesn't look like that child problem of itself exist, but recursion is just helpful.

One case per answer.

# Answer
# Adjusting argument order

E.g. Decide if 3 sticks construct a right triangle:

```
(a,b,c)=>a*a+b*b==c*c|b*b+c*c==a*a|c*c+a*a==b*b  // 47 bytes
f=(a,b,c)=>a<b|a<c?f(b,c,a):a*a==b*b+c*c         // 40 bytes

```

(Yeah the `hypot` solution is also 40, but it's not the point here)

Here it rotates until `a` is one of the largest elements, and there's no need to write the formula three times.
> 6 votes

# Answer
# Another branch of function happens to fit

In Infinite Turtle, all numbers are between 0 and 100, inclusive. There's only saturated increment and decrement by one operation, and isZero condition. Requires to subtract modulo 101.

My solution:

```
SUB101(x,y) := y==0?x:SUB101(x==0?GEN100(x):x-1,y-1)
GEN100(x) := SUB101(x+1,x)==0?x:GEN100(x+1)

```

Here, `SUB101(x+1,x)` returns 1 if `x!=100`, or 0 if `x==100`. `GEN100` is never called inside due to input limit. By reusing `SUB101`, I needn't another `SUB` or `ISEQUAL`.
> 2 votes

---
Tags: tips, recursion
---


title: Negative of an ASCII photo

text:
# Question
Title: Negative of an ASCII photo
# Task

Given an \\$m\times n\\$ binary ascii "photo", return the negative of the photo

**Example:**

```
  #
 # #
#   #
 # #
  #
->
## ##
# # #
 ###
# # #
## ##

```

# General rules:

* This is , so the shortest answer in bytes wins
* Standard rules and default I/O rules apply
* Your output characters must be the same as your input characters (e.g. `["#"," "] -> [" ","#"]`), which you are free to choose (but must be printable characters)
* Your output photo must have the same \\$m\times n\\$ dimensions as the input
* Trailing whitespace is allowed

# Test cases

Input 1:

```
  #
 # #
#   #
 # #
  #

```

Output 1:

```
## ##
# # #
 ###
# # #
## ##

```

Input 2:

```
    # #
  #####
  # #
#####
# #

```

Output 2:

```
#### #
##
## # ##
     ##
 # ####

```

Input 3:

```
##############################################################################################
#  ###  ##       ##  #######  #######       ######  ###  ##       ##       ##  #######      ##
#  ###  ##  #######  #######  #######  ###  ######  ###  ##  ###  ##  ###  ##  #######  ###  #
#       ##     ####  #######  #######  ###  ######  # #  ##  ###  ##       ##  #######  ###  #
#  ###  ##  #######  #######  #######  ###  ######   #   ##  ###  ##  #  ####  #######  ###  #
#  ###  ##       ##       ##       ##       ######  ###  ##       ##  ###  ##       ##      ##
##############################################################################################

```

Output 3:

```
 ##   ##  #######  ##       ##       #######      ##   ##  #######  #######  ##       ######
 ##   ##  ##       ##       ##       ##   ##      ##   ##  ##   ##  ##   ##  ##       ##   ##
 #######  #####    ##       ##       ##   ##      ## # ##  ##   ##  #######  ##       ##   ##
 ##   ##  ##       ##       ##       ##   ##      ### ###  ##   ##  ## ##    ##       ##   ##
 ##   ##  #######  #######  #######  #######      ##   ##  #######  ##   ##  #######  ######

```

# Answer
# Python 3, 31 bytes

```
lambda s:s.translate(9*"# \n ")

```

Try it online!

### How

The `9*"# \n "` is a string that has a "\n" at position 10 which matches its own code point, and at positions 32 and 35 it has copies of "#" and " " so these two are at each other's code point. `str.translate` uses this string as a lookup table replacing each character of `s` by the value associated with its code point. It will leave newlines in place and swap hashes and spaces.
> 50 votes

# Answer
# sed, ~~23~~ 8 bytes

-15 bytes thanks to Digital Trauma

```
y/# / #/

```

Try it online!
> 11 votes

# Answer
# C (tcc), 33 bytes

Function that modifies its input.

```
f(char*s){*s^=1^*s%3;*++s&&f(s);}

```

Try it online!
> 8 votes

# Answer
# Pip, 3 bytes

```
1-_

```

Maybe this is too cheaty?

The solution is a function that takes and returns a list of lists of `0`s and `1`s. Attempt This Online!

Explanation: subtract each number from 1.

---

Here's a **6-byte** version that's on much safer ground rules-wise. It's also a function, and it also uses `0` and `1`, but it takes and returns a multiline string:

```
_TRt01

```

Attempt This Online!

Explanation: Transliterate the characters in `10` (the `t` builtin) to the characters in `01`.
> 8 votes

# Answer
# JavaScript (V8), 25 bytes

```
s=>s.replace(/./g,i=>i^1)

```

Try it online!

Takes input as string of 0's, 1's, and newlines.

Explanation:

```
s => s.replace(
  /./g,       // '.' matches anything but newline, ie. 0 or 1 only.
              // 'g' marks regex as global, to replace everything
  i => i ^ 1  // JavaScript's aggressive type casting forces '0' or '1' string into a number
              // boolean XOR (^) with 1 transforms 0 -> 1 and 1 -> 0
)

```
> 8 votes

# Answer
# Bash \+ coreutils, 12

```
tr '# ' ' #'

```

Try it online!
> 7 votes

# Answer
# Lua, 68 bytes

```
a=io.read('*a')b,d=a.gsub,' 'print((b(b(b(a,'#','!'),d,'#'),'!',d)))

```

Attempt This Online!
> 7 votes

# Answer
# Octave, 13 bytes

```
@(x)['' 67-x]

```

Try it online!

Takes the input as an array of `'# '` characters.

The sum of `'#'` and `' '` is 67, so all we need to do is subtract the input string from 67 and it will "negate" the characters.

Unfortunately we then have to spend a few bytes forcing the output back to being a character array rather than an integer, but ho hum.
> 6 votes

# Answer
# Factor \+ `pair-rocket`, 25 bytes

```
[ "# "=> " #"substitute ]

```

Try it online!
> 5 votes

# Answer
# Vyxal, 1 byte

Try it Online!

Same method as DLosc's 3 byte Pip answer. Takes a list of lists of either 0 or 1.

Simply computes `1 - n` for each digit. Alternatively,

## Vyxal, 3 bytes

```
₀S*

```

Try it Online!

Takes a multiline string of 0s and 1s. The flag, header and footer are for allowing the test cases to be directly pasted in without having to change them.

## Explained

```
₀S*
₀S  # The string "10"
  * # Ring translate the input according to that - change 0 to 1, 1 to 0 and leave newlines as they are.

```
> 5 votes

# Answer
# 05AB1E, 1 byte

Each line is a separated potential program:

```
_
≠
È

```

I/O as a matrix of 1s and 0s.

Try it online or verify all test cases.

Using the actual `#` and spaces as I/O, it would be 5 bytes instead:

```
„# Â‡

```

I/O as multiline strings with `#`s/spaces and potential newlines.

Try it online or verify all test cases.

**Explanation:**

```
      # Transform each 1 to 0 and each 0 to 1 in the (implicit) input-matrix,
_     #  using an ==0 check
≠     #  or !=1 check
È     #  or %2==0 (is_even) check
      # (after which the modified matrix is output implicitly)

„#    # Push string "# "
   Â  # Bifurcate it, short for Duplicate & Reverse copy
    ‡ # Transliterate all "#" to " " and vice-versa in the (implicit) input
      # (after which the modified string is output implicitly)

```
> 5 votes

# Answer
# Haskell, 28 bytes

```
map g
g ' '='#'
g c=min ' 'c

```

Try it online!

Acts on a string with newlines in it.

By the same rules-lawyering as this Pip answer I guess `map$map(1-)` is a valid answer, but I don't really like it.
> 5 votes

# Answer
# Jelly, 4 bytes

```
O^1Ọ

```

A monadic Link that accepts a list of lists of characters (from  and `!`) and yields a list of lists of characters with these characters swapped.

**Try it online!**

### How?

```
O^1Ọ - Link: list of lists of characters
O    - ordinal (vectorises)   : ' ' -> 32  and '!' -> 33
  1  - one                    : 1
 ^   - XOR (vectorises)       : 32  -> 33  and 33  -> 32
   Ọ - character (vectorises) : 33  -> '!' and 32  -> ' '

```

---

If integers are allowed in place of characters as I/O then the one byte Link `¬` would suffice (vectorising loginal NOT).
> 4 votes

# Answer
# , ~~38~~ 30 bytes

Or **23 bytes** by exchanging `function` for `\` using ≥4.1: Attempt This Online!

```
function(x)chartr("# "," #",x)

```

Try it online!
> 4 votes

# Answer
# brainfuck, ~~28~~ 22 bytes

```
,[-------[->+++<]>+.,]

```

Try it online!

Switch `*`(42) and `j`(106). Long to make `\n`(10) same
> 4 votes

# Answer
# Pyth, 13 bytes

```
L:::bdN\#dN\#

```

Try it online!
> 3 votes

# Answer
# APL+WIN, 32 bytes

Prompts for m x n matrix

```
n←(⍴m←⎕)⍴' '⋄((,m=' ')/,n)←'#'⋄n

```

Try it online! Thanks to Dyalog APL Classic
> 3 votes

# Answer
# Retina 0.8.2, 6 bytes

```
T`10`d

```

Try it online! Swaps `0` with `1` but link is to test suite that converts from  `#` to `01` and back. Explanation: `d` is shorthand for `0-9` or `0123456789` so this translates `1` to `0` and `0` to `1` (the extra target characters are ignored).
> 3 votes

# Answer
# Charcoal, 8 bytes

```
ＷＳ⟦⭆ι¬Σκ

```

Try it online! Link is to verbose version of code. Takes input as a list of newline-terminated strings of `0`s and `1`s. Explanation:

```
ＷＳ

```

While there are more strings in the input...

```
⟦⭆ι¬Σκ

```

... logically invert each character's decimal value and output the result on its own line.
> 3 votes

# Answer
# , 14 bytes

-5 bytes by l4m2, using 1-m instead of abs(m-1) and +11 for providing the required function call.

```
function(m)1-m

```

Try it online!

I do personally dislike the freedom of I/O in this challenge and allowing any other input characters than " " and "#". I learned something new from Dominic van Essen's answer actually as I was never aware of that function. But bending the rules to make life easier, nevertheless my answer. Input a 0-1 matrix and just reverse the values.
> 3 votes

# Answer
# Python 3, 21 bytes

```
lambda s:s.swapcase()

```

Takes a multiline string consisting of `a` for spaces and `A` for `#`'s and outputs the string after swapping the case of each letter. Not quite as nice-looking (or interesting) as loopy walt's wonderful answer, but I'm happy to finally write an answer to one of these :)

Try it online!
> 3 votes

# Answer
# Vim, 3 bytes

```
VG~

```

> Your output characters must be the same as your input characters (e.g. \["#"," "\] -\> \[" ","#"\]), which you are free to choose (but must be printable characters)

We will use the upper case and lower case version of any alphabetic character.

### Explanation

1. `V`: Select the whole line
2. `G`: Go to the end of the document
3. `~`: Swap case of the characters

Try it online! (Using: \["q","Q"\] -\> \["Q","q"\])
Try it online! (Adding some replaces to fit the caracters in the examples)
> 3 votes

# Answer
# Vyxal, 1 byte

```
N

```

Try it Online!

A different Vyxal solution. Expects uppercase letters for `#` and lowercase letters for  or vice versa. `N` is the swap case element. The header and footer converts the test case format into the format that the program expects and vice versa.
> 3 votes

# Answer
## Batch, 60 bytes

```
@set/ps=
@set s=%s: =$%
@set s=%s:#= %
@echo(%s:$=#%
@%0

```

Swaps spaces with `#`s. Doesn't work well with file input as it needs to be interrupted with Ctrl+C to exit. Explanation:

```
@set/ps=

```

Read in the next line.

```
@set s=%s: =$%

```

Replace the spaces with `$`s.

```
@set s=%s:#= %

```

Replace the `#`s with spaces.

```
@echo(%s:$=#%

```

Replace the `$`s with `#`s and output the result.

```
@%0

```

Rinse and repeat.
> 2 votes

# Answer
# Charcoal, 19 bytes

```
ＷＳ«Ｆι«≡κ ¦#¦ »Ｍ±Ｌι¹

```

Try it online!
> 2 votes

# Answer
Elisp \+ s.el, 57 bytes

```
(s-replace"-""#"(s-replace"#"" "(s-replace" ""-"(read))))

```
> 2 votes

# Answer
# Haskell, 32 bytes

```
f l=[[x|c<-s,x<-"# ",x/=c]|s<-l]

```

Try it online!

Takes and returns a list of String
> 2 votes

# Answer
# Ruby, 18 bytes

```
->s{s.tr"# "," #"}

```

Try it online!

I suggested this to fix a Ruby answer but disappeared..
> 2 votes

# Answer
# Gema, 7 characters

```
%=.;.=%

```

For this version choose the `%` and `.` characters.

Try it online!

### Gema, 10 characters

```
\#=\ ;\ =#

```

This uses the original `#` and  characters. Unfortunately this needs escaping because

* `#` is metacharacter similar to `*` (`.*` in regex), but recursive
* is metacharacter and means one or more whitespace characters (`\s+` in regex)

Try it online!
> 2 votes

# Answer
# MATL, 4 bytes

```
5\Zc

```

Input is a char matrix containing  and `#`.

Try it online!

### How it works

```
     % Implicit input
5\   % Modulo 5 of (codepoints) of the input chars. This gives 2 for space, 0 for '#'
Zc   % Convert nonzeros to '#' and zeros to char(0)
     % Implicit display. char(0) is displayed as a space

```
> 2 votes

# Answer
# Regex (PCRE2), 19 bytes

```
s/(#)| /${1:+ :#}/g

```

Try it online!
Try it on regex101!

This is a single regex substitution, to be applied once.

In this explanation,  indicates a space:

```
s/         # Match the following:
    (#)    # \1 = match one "#"
|          # or
    ␣      # match one space
/          # Replace with the following:
${1:+␣:#}  # If \1 is set, replace with a space, else replace with "#"
/g         # Enable Global replacement flag

```

# Regex (Boost), 15 bytes

```
s/(#)| /?1 :#/g

```

Try it online!
> 2 votes

# Answer
# Uiua SBCS, 6 bytes

```
⍜(⊛♭)¬

```

Try it!

What it does is flatten  the input, convert it to binary , logical not `¬` it, unbinary it back to characters, then assume the original shape. Under  is the modifier that handles all the function inverses.

Or, using Jordan's method,

# Uiua SBCS, 1 byte

```
¯

```

Just swapcase, but unlike the first answer the letters used must be lower/upper case of the same letter.

Try it!
> 2 votes

# Answer
# J-uby, 9 bytes

Uses `A` and `a` (or any letter and its swapped-case counterpart) as the “pixels.”

```
:swapcase

```

Attempt This Online!
> 2 votes

# Answer
# Husk, 6 bytes

```
†?_aD¶

```

Try it online!

Input & output as single multiline string; 'pixels' are 'A' and 'a' (or any other pair of uppercase & lowercase letters).

Split on newlines (), then, for each () character, if (`?`) it's uppercase (`D`) convert to lowercase (`_`), otherwise convert to uppercase (`a`).

If input is already list of strings, we can drop the  for **5 bytes**. If input is a list of integers (1 and zero) we can have **2 bytes**.
> 1 votes

# Answer
# ///, 55 bytes

```
/
 /
> //
#/
>#// #/ >#//# /#> //>#/->//> /#>//-/ //>//

```

Man, the underscore on the /// link looks bad. Ah, well.

Basically, we first put a cursor (\>) before every run of hashes or spaces, then flip each character after a \>. We need to use an intermediate character (-) to avoid flipping things twice.

Try it online!
> 1 votes

# Answer
# Rust, 70 bytes

```
|s:&str|->String{s.replace("#","?").replace(" ","#").replace("?"," ")}

```

This replaces all occurrences of `#` with `?`, replaces all  with `#`, and then all `?` with . It's quite an effective algorithm.

Try it online!
> 1 votes

# Answer
# Thunno, \\$ 2 \log\_{256}(96) \approx \\$ 1.65 bytes

```
ZX

```

Attempt This Online! or see it with `#` and

Port of Seggan's Vyxal answer. Uses `a` and `A` as the two characters.

## Thunno `N`, \\$ 10 \log\_{256}(96) \approx \\$ 8.23 bytes

```
A\Ziedi1_J

```

Attempt This Online! or see it with `#` and

Uses `0` and `1` as the two characters.

#### Explanation

```
ZX  # Implicit input
ZX  # Swap case of input
    # Implicit output

```

```
A\Ziedi1_J  # Implicit input
A\          # Push a newline
  Zi        # Split the input on newlines
    e       # Map over this list:
     di     #  Convert each character to an integer
       1_   #  Subtract each from one
         J  #  Join the resulting list
            # N flag joins on newlines
            # Implicit output

```
> 1 votes

# Answer
# Japt `-m`, 3 bytes

I/O as an array of binary strings.

```
mèT

```

Try it
> 1 votes

# Answer
# Scala, 63 bytes

Golfed version. Try it online!

```
def f(s:String)=s.map(c=>if(c=='#')' 'else if(c==' ')'#'else c)

```

Ungolfed version. Try it online!

```
def f(s: String): String = s.map {
  case '#' => ' '
  case ' ' => '#'
  case c   => c
}

```
> 1 votes

# Answer
# , 11 bytes

```
'# '{~'#'&=

```

Attempt This Online!

```
'# '{~'#'&=
      '#'&=  NB. vectorized equality check, returns boolean matrix
    {~       NB. index into
'# '         NB. inverted char list

```
> 1 votes

# Answer
# Perl 5 \+ `-p`, 7 bytes

```
y; #;#
```

Try it online!

## Explanation

Uses the `tr`ansliteration syntax (`y///`) but using the implicit `;` from `-p` (`-n`: `while (<STDIN>) {`...`;}`).
> 1 votes

# Answer
# K (ngn/k), 7 bytes

```
" #"@^:

```

Try it online!

* `^:` check which characters in the input are nulls (i.e. spaces/`" "`)
* `" #"@` flip the characters by indexing into `" #"` (0's become s, 1's become `#`s)
> 1 votes

# Answer
# Swift 5.9, 38 bytes

```
let f={($0+[]).map{($0+[]).map{1-$0}}}

```

`f(_:)`'s type is `([[Int]]) -> [[Int]]`. The two "characters" are `1` and `0`.
> 0 votes

---
Tags: code-golf, string, ascii-art
---


title: 100 Day Countdown

text:
# Question
Title: 100 Day Countdown
It is common to start countdowns 100 days prior to an event, probably because of our base 10 system. Examples of this can be found everywhere:

* 100 days until your birthday
* 100 days until the wedding
* 100 days until the election
* 100 days until our graduation
* 100 days until her due date
* 100 days until football season
* 100 days until you get the Fanatic badge

You get the picture. It seems that the 100th day before an event is second place only to the actual event. So for this challenge, I need to know what the date will be in 100 days, so that I can determine what I should start counting down too.

## Input

No input

## Output

The date 100 days from the current date based on the standard Gregorian Calendar (Make sure to account for leap years). Output is flexible as long as the date format is human read-able (eg `2016-10-8`, `10-8-16`, `[ 2016, 10, 8 ]`, `10/8/16 12:00:00 AM`).

## Winning

Code golf: shortest code in bytes

---

### Examples

100 days from today (Apr 5th, 2017) is Friday, July 14 2017.

```
Current                Future
-------                ------
01/01/2001 +100        04/11/2001
01/01/2004 +100        04/10/2004
01/01/1900 +100        04/11/1900
01/01/2000 +100        04/10/2000

07/04/2017 +100        10/12/2017
10/31/2017 +100        02/08/2018
12/25/2017 +100        04/04/2018

08/29/1941 +100        12/07/1941
06/03/2001 +100        09/11/2001

```

# Answer
# Excel, 10

```
=NOW()+100

```

### Demonstration
> 42 votes

# Answer
# Bash, ~~17~~ ~~16~~ ~~15~~ ~~14~~ 13 bytes

```
date -d100day

```

It turns out the `date` command takes some pretty flexible input for relative timings. You can also do things like `1 year`, `1 week ago`, `yesterday`, etc. It's pretty cool.

-1 byte by realizing that bash does not care about grammar.
-1 byte because the space between `100` and `day` is unnecessary.
-1 byte because I don't need quotes anymore because I don't have a space in the string.
-1 byte by removing the space after `-d` (thanks ASCII-only!)
> 20 votes

# Answer
# PowerShell, 10 bytes

```
(date)+1e2

```

Thanks to ConnorLSW for the +1e2 trick.

It appears that doubles (`1e2` is a double) are also added as days.

### Previous version, 12 bytes:

```
(date)+"100"

```

Apparently you can add strings to dates in PowerShell. The string `"100"` is converted into a 100 days-`TimeSpan`.
> 10 votes

# Answer
# Mediawiki, 19bytes

```
{{#time:r|+100day}}

```

You may try it with wikipedia's sandbox
> 8 votes

# Answer
# PHP, 28 bytes

```
<?=date(Y_m_d,time()+864e4);

```

human readable version, 35 bytes:

```
<?=date(Y_m_d,strtotime("100day"));

```

almost readable, 34 bytes:

```
<?=date(Y_m_d,strtotime(1e2.day));

```

-4 bytes if also printing the time is accepted: replace `Y_m_d` with `r` or `c`.

It´s National Holiday in France in 100 days.
> 6 votes

# Answer
# Ruby, 16 bytes

```
p Time.now+864e4

```

Try it online!
> 5 votes

# Answer
# Javascript, ~~29~~ ~~26~~ 25 bytes

Saved 3 bytes thanks to @ASCII-only!

Saved 1 byte thanks to @JohanKarlsson

```
new Date(+new Date+864e7)

```

```
document.body.innerHTML=new Date(+new Date+864e7)
```
> 5 votes

# Answer
## SQL (PostgreSQL), 19 Bytes

```
SELECT now()+'100d'

```
> 5 votes

# Answer
# Vim, 27 bytes

```
:r!date "+\%F" -d"+100 day"

```

try it online!

Edit: Removed unnecessary space char.
> 4 votes

# Answer
# MATL, 9 bytes

```
Z'100+1XO

```

Output format is `15-Jul-2017` (which I find most readable). Change `1XO` to `2XO` to get the format used in the examples, `07/15/17`.

Try it online!

### Explanation

```
Z'      % Push current date and time as a serial date number
100+    % Add 100
1XO     % Convert to string with format 'dd-mmm-yyyy'. Implicitly display

```
> 4 votes

# Answer
**SQL (Microsoft), 35 31 bytes**

```
SELECT DATEADD(D,100,GETDATE())

```
> 4 votes

# Answer
# Mathematica, ~~26~~ 21 bytes

-5 bytes thanks to @KiranLinsuain!

```
Today+Quantity@"100d"

```

If including the time is permitted, then we can save 2 bytes:

```
Now+Quantity@"100d"

```
> 3 votes

# Answer
# C#, 103 97 bytes

*Thanks to raznagul for saving 6 bytes!*

```
using System;class P{static void Main(){Console.Write(DateTime.Now.AddDays(100).ToString("d"));}}

```

Full program which reads the current date, adds 100 days and displays the result in `M/d/YYYY` format.

You can change the date format by adding a few more bytes:

```
using System;class P{static void Main(){Console.Write(DateTime.Now.AddDays(100).ToString("d-M-yyyy"));}}

```

---

To eliminate boilerplate code - C# isn't exactly known to be very compact - an anonymous function can be used:

# C# lambda, 49 43 bytes

```
()=>DateTime.Now.AddDays(100).ToString("d")

```

Full program:

```
using System;

class P
{
    static void Main()
    {
        Func<string> f =
        ()=>DateTime.Now.AddDays(100).ToString("d");

        Console.WriteLine(f());
    }
}

```
> 3 votes

# Answer
# Java 8, ~~77~~, 61 bytes

```
()->System.out.print(java.time.LocalDate.now().plusDays(100))

```

Try it online!
> 3 votes

# Answer
# Noodel, 8 bytes

```
]5@LaƇ⁺ƈ

```

Try it:)

---

## How it works

```
]5@LaƇ⁺ƈ
]5@La    # The string "]5@La" gets pushed onto the stack which in base 98 represents 8,640,000,000.
     Ƈ   # Pushes an integer that represents the current time where highest resolution is milliseconds.
      ⁺  # Add the time and the string which will be interpreted as 8,640,000,000ms.
       ƈ # Convert the integer to human readable time.
         # Implicitly output to the screen.

```

```
<div id="noodel" code="]5@LaƇ⁺ƈ" input="" cols="80" rows="2"/>

<script src="https://tkellehe.github.io/noodel/noodel-latest.js"></script>
<script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script>
```
> 3 votes

# Answer
# C, ~~87~~ ~~46~~ 44 bytes

*saved 2 bytes thanks to Albert Renshaw*

```
f(){time_t t=time(0)+864e4;puts(ctime(&t));}

```

I realized the output is flexible enough to allow for day of week and time, so there's no need to use `localtime` or the `tm` structure at all.

### Old answer

```
f(){time_t t=time(0)+8640000;char b[9];strftime(b,9,"%d-%m-%y",localtime(&t));puts(b);}

```

Based on Khaled.K's answer, but instead of messing with the `tm` structure, adds the number of seconds equivalent to 100 days directly to the `time_t` value. It also prints only the date, without time or day of week.

As it should happen on a golfed program, some ugly warnings are generated on compilation.

Try it online!

### Ungolfed:

```
f(){
    // Current time + 100 days
    time_t t=time(0)+8640000;
    // Buffer for printing formatted time
    char b[9];
    // Print the time in format dd-mm-yy to buffer
    strftime(b,9,"%d-%m-%y",localtime(&t));
    // print buffer
    puts(b);
}

```
> 3 votes

# Answer
# JavaScript, 42 bytes

```
(d=new Date()).setDate(d.getDate()+100)&&d

```

```
setInterval(_=>document.body.innerHTML=(d=new Date()).setDate(d.getDate()+100)&&d,1000)
```
> 2 votes

# Answer
# IBM/Lotus Notes Formula, 29 bytes

```
@Adjust(@Today;0;0;100;0;0;0)

```

Unfortunately `@Adjust` requires the trailing `0's` for the missing `hh:mm:ss`.

If we were allowed to display the time as well then changing `@Today` to `@Now` would save 2 bytes for 27.
> 2 votes

# Answer
## JavaScript (ES6), 44 bytes

```
_=>new Date(Date.now()+864e7).toDateString()

```

25 bytes if returning a date with the time is acceptable:

```
_=>Date(Date.now()+864e7)

```
> 2 votes

# Answer
# 30 bytes

**Mysql!**

```
select NOW()+INTERVAL 100 DAY;

```

**SQLite**

```
SELECT date('now','+100 day');

```
> 2 votes

# Answer
# C, ~~120~~ 113 bytes

```
#include <time.h>
f(){time_t t=time(0);struct tm*tm=localtime(&t);tm->tm_mday+=100;t=mktime(tm);printf("%s",ctime(&t));}

```

**Live Demo**

```
#include <stdio.h>
#include <time.h>

void PrintDatePlus100days()
{
    // obtain current time
    time_t t = time( 0 );

    // convert to datetime struct
    struct tm *tm = localtime( &t );

    // add 100 days
    tm->tm_mday += 100;

    // convert to time_t
    t = mktime( tm );

    // print time in readable format
    puts( ctime( &t ) );
}

```
> 2 votes

# Answer
# F# (53 bytes)

```
printf"%s"(DateTime.Now.AddDays(100.0).ToString("d"))

```
> 2 votes

# Answer
## Swift 3, 39 bytes

```
print(Date(timeIntervalSinceNow:864E4))

```
> 2 votes

# Answer
# R (REPL), 14 bytes

```
Sys.Date()+100

```

Try it on Ideone.
> 2 votes

# Answer
**PowerShell, 23**

```
(get-date).adddays(100)

```

This is my first ever try, so please give me constructive feedback. Thanks!
> 2 votes

# Answer
# Python, 63 bytes

```
from datetime import*
print(datetime.now()+timedelta(days=100))

```

Very simple solution really. Because the `datetime.now()` result is the same `type` as the result of `timedelta`, it happily adds the two together.
> 1 votes

# Answer
# JavaScript, 38 Bytes

```
d=new Date;d.setDate(d.getDate()+100);d

```

A little bit shorter than ASCII-only answer.

```
document.write(eval("d=new Date;d.setDate(d.getDate()+100);d"))
```
> 1 votes

# Answer
# Golang, 58 bytes

```
import ."time"
func f(){Println(Now().AddDate(0, 0, 100))}

```

Full Program

```
package main

import . "time"
import . "fmt"

func main() {
    Println(Now().AddDate(0, 0, 100))
}

```

try it online!
> 1 votes

# Answer
**Oracle, 34 bytes**

```
SELECT CURRENT_DATE+100 FROM DUAL;

```
> 1 votes

# Answer
# Python 2 + Pandas 0.19.1, 56 51 bytes

```
from pandas import*
print Timestamp('now','D')+100

```
> 1 votes

# Answer
# SAS, 52 bytes

```
%put%sysfunc(intnx(day,%sysfunc(date()),100),date9.)

```
> 1 votes

# Answer
## R, ~~16~~ ~~14~~ 21 bytes

```
print(Sys.Date()+100)

"2017-07-16"

```
> 1 votes

# Answer
## VBA, 8 bytes

```
?now+100

```

output:

```
2017-07-16 10:13:19

```

Works in the Immediate Window. Beats Excel by 2 bytes by skipping parentheses.
> 1 votes

# Answer
## JavaScript, 21 bytes

```
Date(+new Date+864e7)

```

Actually, you don't really need `new` before Date.

Based on this post.

```
document.body.innerHTML = Date(+new Date+864e7);
```
> 1 votes

# Answer
# Perl 6, 20 bytes

```
print Date.today+100

```

Try it online!
> 1 votes

# Answer
## Pyke, 6 bytes

```
wVs2h

```

Try it online! (doesn't use literal because I can't figure out how to embed it)

```
w      -  get 100 in 2 bytes
  Vs2h - Repeat ^ times
   s2  -   increment the day part
     h -  strip the time part

```

Hexdump:

```
77 84 56 73 32 68

```
> 1 votes

# Answer
# AWK, 43 bytes

```
BEGIN{print strftime("%F",systime()+864e4)}

```

Could save a few bytes if run using some input... maybe... using something like:

```
{$0=strftime("%F",systime()+864e4)}1

```

and running the code like:

```
awk '{$0=strftime("%F",systime()+864e4)}1'<<<1

```

But then we have to account for the bytes used to do that. So I'll stick with simplicity :)
> 1 votes

# Answer
# VBScript, 18 bytes

```
dateadd(d,100,now)

```
> 1 votes

# Answer
# k6 and , 8 bytes

```
.z.d+100

```

Apparently, `.z.d` returns the current date, and the default units when adding to dates are days.
> 1 votes

# Answer
# Wolfram Language, 19 bytes

```
DatePlus[Today,100]

```

Kinda self-explanatory but let's explain.

**DatePlus** (From Wolfram Language Reference)

> **DatePlus**\[date,{n,"unit"}\] gives the date n units after date.
>
> Possible offset units are "Year", "Quarter", "Month", "Week", "Day", "Hour", "Minute", "Second", "Weekday", "Weekend", Monday through Sunday, "EndOfMonth", and "BusinessDay".
> Offsets can also be specified using the Quantity framework.
> {y,m,d} is taken to be equivalent to {y,m,d,0,0,0} etc.
> DatePlus\[date,offset\] gives results in the same general format as date.
> When date is a list, the result has the same length as date, possibly extended to include the smallest unit in offset. »
> When date is a string, the result is in the form specified by $DateStringFormat.

**Today** (From Wolfram Language Reference)

> **Today
** gives a DateObject representing the current day.

So basically, it just adds 100 days to the current date. See screenshot below.
> 1 votes

# Answer
# Matlab/Octave, 16 bytes

```
datestr(now+100)

```

Pretty much self-explanatory and (a bit) boring, but could not be missing!
> 1 votes

# Answer
# Japt, 9 bytes

```
Ð864e7+Kj

```

Test it

My first Japt answer!

A port of the existing JS answer.
> 1 votes

# Answer
# NodeJS, 96 bytes

```
require('http').createServer(function(q,s){s.end(':'+new Date(Date.now()+(864e7)))}).listen(8e3)

```

My first codegolf attempt ever, but I can't find anything to make it shorter.
> 0 votes

# Answer
## HP‑41C series, 16 Bytes

This program requires an HP‑41CX or an HP‑41C/CV with a time module plugged in. After energizing the clock’s electronics, the clock is set to January 1, 1900, 0:00 a. m, so set the clock first.

```
01♦LBL⸆T           5 Bytes  global label requires 4 + (length of string) Bytes
02 DATE            2 Bytes  obtain current date in MM.DDYYYY or DD.MMYYYY format
   NULL            1 Byte   invisible Null byte before numbers
03 100             3 Bytes  push 100 on to the stack (Y ≔ date; X ≔ 100)
04 DATE+           2 Bytes  add 100 days (X) to today’s date (Y) and yield date
05 FIX 6           2 Bytes  ensure _all_ digits of the date are visible
06 RTN             1 Byte   `RTN` does not affect local label search

```

The `X` register (the top of the stack) now contains the date in `MM.DDYYYY` format (or `DD.MMYYYY` should you have changed that by invoking the `DMY` command).

**Limitations**: The result of the `DATE+` and other time‑related calculation operations can be “any date from October 15, 1582 (the beginning of the Gregorian calendar) through September 10, 4320” (quoted from the HP‑41CX Owner’s Manual Vol. 2).
> 0 votes

# Answer
# Swift 5.9, 53 bytes

```
import Foundation
print("\(Date()+864e4)".prefix(10))

```
> 0 votes

---
Tags: code-golf, date
---