title: Happy Birthday, Finland!

text:
# Question
Title: Happy Birthday, Finland!
# Introduction

As is known, in 2017, Finland celebrates its 100 years of independence. To mark the occasion, it is your job to produce a Finnish flag for everyone's enjoyment.

# Challenge

Create a program or a function that produces the flag of Finland (the grey border is there for presentation purposes only):

### Flag specifications

* The ratio of the flag is `18:11`, with the cross being `3` units thick, giving a horizontal ratio set of `5:3:10` and a vertical ratio set of `4:3:4`.
* The picture must be at least `180 x 110` pixels in size, or in case of ASCII art, `90 x 55` characters.
* There is no official RGB colour for the blue, but use the closest approximation of `(0, 53, 128)`. If your system doesn't support RGB values, use `blue`.
* For the white colour, use RGB `(255, 255, 255)` or `white`.

### Not so fast

As drawing the Finnish national flag would be simpler than last year's Icelandic challenge, we'll have to ramp up the difficulty a bit. Given that Finland's Independence Day is on 6 December, the decimal number `100` must appear somewhere on the flag when the date in Finland (UTC+02:00) is `2017-12-06` or later (your code should not assume that the machine it's running on is set to a particular timezone). Before the date, the number must not be there. The number must be printed in black (RGB `(0, 0, 0)` or `black`) but its placement and font parameters are up to you.

An example of such a render (again, ignore the border):

For testing purposes, it would be nice to include two additional versions of your solution, one with a fixed date in the past and one in the future.

# Rules

Standard loopholes are forbidden, as are built-in flag images/libraries. Also, your code must not take any input.

Finns don't like small talk, and this is , so don't waste characters!

# Answer
# C (Windows), 361 bytes

```
#import<time.h>
#import<windows.h>
C(x){SetConsoleTextAttribute(GetStdHandle(-11),x);}F(I,N,l,a,n,d)time_t n;struct tm*d;{system("mode 90,65");time(&n);d=gmtime(&n);n=d->tm_year<<24|d->tm_mon<<16|d->tm_mday<<8|d->tm_hour;for(a=l=I=15;I++<70;a=l=I<35|I>49?15:9)for(N=n>1963656468&I<17?C(240),printf("100"):0;N++<90;a=N-25?a:9,a=N-40||l==9?a:15)C(a),putchar(70);}

```

**Unrolled:**

```
#import <time.h>
#import <windows.h>

C(x)
{
    SetConsoleTextAttribute(GetStdHandle(-11),x);
}

F(I,N,l,a,n,d) time_t n;struct tm*d;
{
    system("mode 90,65");

    time(&n);
    d = gmtime(&n);
    n = d->tm_year<<24 | d->tm_mon<<16 | d->tm_mday<<8 | d->tm_hour;

    for(a=l=I=15; I++<70; a=l=I<35|I>49?15:9)
        for(N=n>1963656468&I<17?C(240),printf("100"):0; N++<90; a=N-25?a:9,a=N-40||l==9?a:15)
            C(a), putchar(70);
}

```

**Output:**

**Output when `UTC time >= 2017-12-05-22-00`:**

Add the following in the code after `d=gmtime(&n);` to try it:

```
d->tm_year = 117;
d->tm_mon = 11;
d->tm_mday = 5;
d->tm_hour = 21;

```
> 24 votes

# Answer
# PHP + SVG(HTML5), 147 137 123 bytes

SVG code by Neil

https://codegolf.stackexchange.com/a/149850/66061

```
<svg><path d=180v110 fill=#fff></path><path d=M0,40h50V0h30v40h100v30H80v40H50V70H0 fill=#005580></path><?=time()<1512511200?:'<text x=9 y=15>100';

```

Update: Thanks to Shaggy for helping me save 10 bytes.

```
<svg><path d=180v110 fill=#fff /><path d=M0,40h50V0h30v40h100v30H80v40H50V70H0 fill=#005580 /><?=time()<1512511200?:'<text x=9 y=15>100';

```

Update 2: Smart idea by Ismael Miguel, thanks for saving 14 bytes

```
<svg><path d=180v110 /><path d=M0,40h50V0h30v40h100v30H80v40H50V70H0 fill=#005580 /><?=time()<1512511200?:'<text y=19>100';

```

Normal

After 6th Dec +2 hours
> 16 votes

# Answer
# Röda, ~~252~~ 250 bytes

```
{s={|w,h|[` width="$w" height="$h" `]}r=`><rect`f=`" fill="#003580"/`
[`<svg`,s(18,11),r,s(18,11),`fill="#fff"/`,r,s(18,3),`y="4$f`,r,s(3,11),`x="5$f>`]
[`<text y="9" font-size="2">100</text>`]if{}|[[exec("date","+%s")]&"">="1512511200
"]
[`</svg>`]}

```

Try it online!
> 13 votes

# Answer
# C#, 407 400 277 bytes

Weird how `ForegroundColor =0` is allowed

*Saved 1 byte thanks to TuukkaX*

*Saved 67 bytes thanks to Adam*

```
()=>{for(int x=0,y;x<90;x++)for(y=0;y<55;y++){BackgroundColor=(ConsoleColor)15;if(x>24&x<41|(y>19&&y<36))BackgroundColor=(ConsoleColor)9;SetCursorPosition(x,y);Write(' ');}if(new DateTime(2017,12,5,22,0,0)<DateTime.UtcNow){SetCursorPosition(1,1);ForegroundColor=0;Write(100);}}

```

ungolfed for testing:

```
using System;
using static System.Console;
class P
{
    static void Main()
    {
        Action func = () =>
        {
            for (int x = 0,y; x < 90; x++) for (y=0; y < 55; y++)
                {
                    BackgroundColor = (ConsoleColor)15;
                    if (x > 24 & x < 41 | (y > 19 && y < 36))
                        BackgroundColor = (ConsoleColor)9;
                    SetCursorPosition(x, y);
                    Write(' ');
                }

            if (new DateTime(2017, 12, 5, 22, 0, 0) < DateTime.UtcNow)
            {
                SetCursorPosition(1, 1); ForegroundColor =0; Write(100);
            }
        };
        func();
        ReadLine();
    }
}

```

for testing 100:

```
using System;
using static System.Console;
class P
{
    static void Main()
    {
        Action func = () =>
        {
            for (int x = 0,y; x < 90; x++) for (y=0; y < 55; y++)
                {
                    BackgroundColor = (ConsoleColor)15;
                    if (x > 24 & x < 41 | (y > 19 && y < 36))
                        BackgroundColor = (ConsoleColor)9;
                    SetCursorPosition(x, y);
                    Write(' ');
                }

            if (new DateTime(2017, 12, 2, 22, 0, 0) < DateTime.UtcNow)
            {
                SetCursorPosition(1, 1); ForegroundColor =0; Write(100);
            }
        };
        func();
        ReadLine();
    }
}

```
> 11 votes

# Answer
# Python 2, ~~247~~ ~~246~~ ~~230~~ ~~210~~ 189 bytes

```
import time
print'P3',180,110,255
w,b='255 '*3,'0 52 128 ';B=['0 '*3,w][time.gmtime()<(2017,12,5,22)]
a=w*40+b*30+w*100
x=w*10+a;y,z=w+B+w+B*3+w+B*3+a,(w+B)*5+a
print y+z+y+x*37+b*5400+x*40

```

Try it online!

Prints a .ppm image:

Normal flag

Flag with 100
> 9 votes

# Answer
# Mathematica, 129 bytes

```
If[AbsoluteTime@Date[]<3721507200,s="",s=100];Graphics@{s~Text~{9,9},RGBColor[0,.2,.5],{0,4}~(R=Rectangle)~{18,7},{5,0}~R~{8,11}}

```

before..
after..

you can always test it on Wolfram Sandbox
(paste the code and hit Shift-Enter)
> 9 votes

# Answer
# Processing.org / Java ~~191~~ 188 bytes

-3 bytes thanks to KevinCruijssen

```
import java.util.*;void setup(){size(180,110);background(-1);fill(0);if(new Date().getTime()>=15125256e6D)text("100",0,9);noStroke();scale(10);fill(#003580);rect(5,0,3,11);rect(0,4,18,3);}

```
> 7 votes

# Answer
# Excel VBA, ~~120~~ ~~118~~ 117 Bytes

Anonymous VBE immediate window function that takes no input and outputs the the Finnish flag and if Finland is greater than 100 years old a `100` on that flag. This is done with respect to the Easter Timezone of the United States, as there is no way for Excel or Excel VBA to determine timezone without add-ins or accessing the internet.

```
Cells.RowHeight=48:Cells.Interior.Color=-1:[F1:H11,A5:R7].Interior.Color=8402176:If Now>=#12/5/17 19:0#Then[B2]=100

```

### Output

If Finland is younger than 100 years old

If Finland is older than 100 years old

-2 Byte for changing `If #12/5/17 19:00#<=Now Then[B2]=100` to `If Now>=#12/5/17 19:0#Then[B2]=100`

-1 Byte for use of `Cells` rather than `[A1:R11]`
> 7 votes

# Answer
# Python 3, 143 141 135 bytes

Uses ANSI escape for colors, uses five spaces or " 100 " as a colored string so that I don't need to specially print "100" somewhere on the flag. Length 5 because of width, because `90/5 == 90//5`. The string being used is getting defined in row 1. Then we iterate 55 round (height), on every iteration `v` is set to string with color \[Blue, BrightWhite\] and selected index is boolean `row<20 or r>34`. We multiply that result by 5 again (width dimensions: 25:15:50 so total width is 90). Then we print out `v + Blue + Blue + Blue + v + v + Black` where `v` is either Blue or BrightWhite. To clarify printing: width of `v` is 25 chars, width of Blue (`e%44*3`) is 15 and width of `v*2` is 50. `25+15+50` is 90 which is the width and follows the dimensions required in the task! Quite messy summary but I guess it's better than nothing.

```
import time;e="\033[30;%dm "+[" "*4,"100 "][time.time()>1512511200]
for r in range(55):v=e%[107,44][19<r<35]*5;print(v+e%44*3+v*2+e%40)

```
> 7 votes

# Answer
# MATLAB, ~~133~~ ~~130~~ 123 bytes

*~~3~~ 10 bytes sabed thanks for @flawr!*

```
r=1:180;r(51:80)=0;imshow(r(11:120)'*r,[0 .2 .5;1 1 1])
if datenum(datetime('now','T','UTC+2'))>=737035 text(9,9,'100'),end

```

This uses `[0, 51, 128]` for the blue color. The size of the image is 180×110 pixels.

Sample run:

Sample run with the text (changing `737035` to `0` in the code so that the text is shown on any day):
> 5 votes

# Answer
## JavaScript (ES5) + SVG(HTML5), ~~189~~ 179 bytes

```
document.write('<svg><path d=M0,0h180v110H0z fill=#fff /><path d=M0,40h50V0h30v40h100v30H80v40H50V70H0Z fill=#005580 />'+(Date.now()<15125112e5?'':'<text x=0 y=30 fill=#000>100'))
```

```
<body color=grey bgcolor=silver>
```

(HTML to show that the colour requirements are being met.) Edit: Saved 10 bytes thanks to @Shaggy. Outputs:

```
<body color=grey bgcolor=silver>

<svg><path d=M0,0h180v110H0z fill=#fff /><path d=M0,40h50V0h30v40h100v30H80v40H50V70H0Z fill=#005580 />
```

```
<body color=grey bgcolor=silver>

<svg><path d=M0,0h180v110H0z fill=#fff /><path d=M0,40h50V0h30v40h100v30H80v40H50V70H0Z fill=#005580 /><text x=0 y=30 fill=#000>100
```
> 4 votes

# Answer
# Python 3 with Pillow, ~~213~~ ~~212~~ 211 characters (Unix) and ~~217~~ 216 characters (Portable)

This is the Unix version. I realized after posting that the time returned by `time()` does not necessarily have its epoch on 1 Jan 1970, so it is not necessarily portable.

```
b=8402688;from PIL import Image,ImageDraw as d
j=Image.new('RGB',(180,110),~1);r=d.Draw(j);R=r.rectangle
R([50,0,79,109],b);R([0,40,180,69],b);import time
r.text((9,9),'100'*(time.time()>=0x5a273300),0)
j.show()

```

This is the portable code, 4 bytes more, it uses `gmtime` with tuple comparison so it should work reliably on Windows too.

```
import time
from PIL import Image,ImageDraw as d
b=8402688
j=Image.new('RGB',(180,110),~1)
r=d.Draw(j)
R=r.rectangle
R([50,0,79,109],b)
R([0,40,180,69],b)
r.text((9,9),'100'*(time.gmtime()>(2017,12,5,22)),0)
j.show()

```

The images are displayed in a window. Really difficult to make it consume less characters. Even `time.time` returns a `float` so `>0x5a273299` would not be quite so correct, or `>0x5a273300` would be off by a microsecond.

>
> 4 votes

# Answer
# Java 342 368 361 321 317 (299+18) bytes

## Golfed

```
import java.awt.*;()->new Frame(){{setBackground(Color.WHITE);setUndecorated(0<1);setSize(180,110);setVisible(0<1);}public void paint(Graphics g){g.setColor(new Color(0,53,128));g.fillRect(50,0,30,110);g.fillRect(0,40,180,30);g.setColor(Color.BLACK);if(System.currentTimeMillis()>15125112e5)g.drawString("100",9,9);}}

```

## Ungolfed

```
import java.awt.*;
() -> new Frame() {
    {
        setBackground(Color.WHITE);                     //Color Objects ARE just RGB values
        setUndecorated(0 < 1);                          //Get's ride of title bar
        setSize(180, 110);
        setVisible(0 < 1);
    }
    public void paint(Graphics g) {
        g.setColor(new Color(0, 53, 128));              //The special blue color
        g.fillRect(50, 0, 30, 110);
        g.fillRect(0, 40, 180, 30);
        g.setColor(Color.BLACK);
        if (System.currentTimeMillis() > 15125112e5)    //Time Condition
            g.drawString("100", 9, 9);
    }

```

## Result

## Credits

40 bytes saved by Olivier Grégoire for using lambda.
4 bytes saved by Kevin Cruijssen for Long formatting.
2 bytes saved by user902383 for hex formatting.
> 4 votes

# Answer
# Tcl/Tk, 135 bytes

***Must be run in the interactive shell***

```
gri [can .c -bg #FFF]
lmap C {"52 2 82 112" "2 42 182 72"} {.c cr r $C -f #003580 -w 0}
if [clock se]>1512518520 {.c cr t 19 9 -te 100}

```

**Before 2017/12/06 02:00 GMT**

**After 2017/12/06 02:00 GMT**
> 4 votes

# Answer
## bash, 198

```
p()(printf "%-$1b$3" "\e[$2m")
r()(for i in `seq $1`;{ $2;})
a()(p 31 107
p 20 44
p 56 30\;107 "${1:-   }"
p 0 0 '
')
b()(p 95 44
p 0 0 '
')
r 20 a
r 15 b
r 19 a
((`date +%s`>1512511199))&&a 100||a

```
> 3 votes

# Answer
## bash and imagemagick, 135

```
((`date +%s`>1512511199))&&x=100
convert -size 150x80 xc: -background \#003580 -splice 30x30+50+40 -draw "fill black text 9,9 '$x'" x:

```
> 3 votes

# Answer
## vim, 147

I really like this challenge ☺. © is escape.

```
sy on
set ft=c
hi Normal ctermfg=4 ctermbg=7
hi Number ctermfg=0 ctermbg=7
norm 90i ©26|15r█Y40pMVr█Y14Pk
if localtime()>1512511199
norm R100

```
> 3 votes

# Answer
# Imperative Tampio, 239 bytes (non-competing)

```
Kun iso sivu avautuu,se näyttää tekstin"<svg><path d=180v110 /><path d=M0,40h50V0h30v40h100v30H80v40H50V70H0 fill=#005580 />"ja,jos nykyinen aika millisekunteina on suurempi kuin 1512511200000,niin se näyttää tekstin"<text y=19>100".

```

> **Kun** iso sivu *avautuu*,se *näyttää* **tekstin**`"<svg><path d=180v110 /><path d=M0,40h50V0h30v40h100v30H80v40H50V70H0 fill=#005580 />"`**ja**,**jos** nykyinen aika millisekunteina **on** **suurempi** **kuin** `1512511200000`,**niin** se *näyttää* **tekstin**`"<text y=19>100"`.

Online version

Translation:

> When the big page opens, it will show the text `"<svg><path d=180v110 /><path d=M0,40h50V0h30v40h100v30H80v40H50V70H0 fill=#005580 />"` and, if the current time in milliseconds is greater than `1512511200000`, it will show the text `"<text y=19>100"`.

SVG was taken from this answer by th3pirat3 (and Neil, appearently).

This program is written in a new version of Tampio I have been working on. Those of you who know Finnish can see that it is almost readable. I marked the answer as non-competing because this language was published after this challenge.

To run this program, either go to the online version above that contains the compiled JS version of the program or download the compiler from its Github page. To compile the program, run `python3 tampio.py -p program.itp >program.html`.

Tampio is not a golfing language by any measure, but due to the better svg code, it actually beat Röda... I was a little surprised.
> 3 votes

# Answer
# HTML + CSS + Javascript, 339 bytes

```
<style>#f{width:180px;height:110px;position:relative}.b{background-color:#003580;position:absolute}.v{left:27.78%;width:16.67%;height:100%}.h{top:36.36%;height:27.27%;width:100%}</style><div id="f"><div class="b v"></div><div class="b h"></div></div><script>if(Date.now()>1512525600000)document.getElementById('f').innerHTML+=100;</script>

```

Here's the same solution trimmed down to 260 bytes, which assumes your viewing port has the proper 18:11 ratio.

```
<style>.b{background-color:#003580;position:absolute}.v{left:27.78%;width:16.67%;height:100%}.h{top:36.36%;height:27.27%;width:100%}</style><div class="b v"></div><div class="b h"></div><script>if(Date.now()>1512525600000)document.body.innerHTML+=100;</script>

```

You can knock a 0 off of the timestamp in either solution to see the "100" appear.
> 1 votes

# Answer
# HTML + Javascript, 329 bytes

I shamelessly stole the date-checking part from @jstnthms. Basically I just write crude html table with correct row/col ratios, `th` being the blue parts. Tested on IE and Chrome.

```
<body onload="h=[4,3,4];w=[5,3,10];m=50;s='<style>*{border-spacing:0;padding:0;}th{background:#003580;}</style><table>';for(y in h){s+='<tr height='+(m*h[y])+'>';for(x in w){c=(y==1||x==1)?'h':'d';s+='<t'+c+' width='+(m*w[x])+'>'+(x+y<1&&Date.now()>15125112e5?'100':'')+'</t'+c+'>';}s+='</tr>';}s+='</table>';document.write(s);">

```
> 1 votes

# Answer
# Perl 5, 139 bytes

```
($w,$b,$r)=map"\e[${_}m","47;30",44,0;$_=$w.$"x25 .$b.$"x15 .$w.$"x50 .$r.$/;$_=$_ x12 .s/7/4/gr x9 .$_ x12;time<1512511200||s/   /100/;say

```

to be launched

```
perl -E '($w,$b,$r)=map"\e[${_}m","47;30",44,0;$_=$w.$"x25 .$b.$"x15 .$w.$"x50 .$r.$/;$_=$_ x12 .s/7/4/gr x9 .$_ x12;time<1512511200||s/   /100/;say'

```

ratio was changed because of character ratio height/width = 1.66 (5/3) otherwise with original ratio :

```
($w,$b,$r)=map"\e[${_}m","47;30",44,0;$_=$w.$"x25 .$b.$"x15 .$w.$"x50 .$r.$/;$_=$_ x20 .s/7/4/gr x15 .$_ x20;time<1512511200||s/   /100/;say

```
> 1 votes

# Answer
# Racket 6.10 with 2htdp/image, 202 bytes

```
(let*([w 180][h 110][p(λ(w h x y o)(place-image(rectangle w h'solid(color 0 53 128))x y o))][b(p w 30 90 55(p 30 h 60 55(empty-scene w h)))])(if(>(current-seconds)1512536400)(overlay(text"100"9'b)b)b))

```

Ungolfed:

```
(let* (
       [flag-width 180]
       [flag-height 110]
       [place-rect (λ (width height x-pos y-pos other-pos)
                     (place-image
                      (rectangle width height 'solid (color 0 53 128))
                      x-pos y-pos other-pos))]
       [flag (place-rect
              flag-width 30 90 55
              (place-rect
               30 flag-height 60 55
               (empty-scene flag-width flag-height)))]
       )
  (if (> (current-seconds) 1512536400)  ; If Finland is 100 years old
      (overlay (text "100" 9 'b) flag)  ; add "100" to the flag
      flag))                            ; otherwise just the flag

```
> 1 votes

# Answer
# Small Basic, 300 bytes

A Script that takes no input and outputs to the `TextWindow` object.

```
GraphicsWindow.BrushColor=0
If Clock.Year*10000+Clock.Month*100+Clock.Day>=20171206Then
GraphicsWindow.DrawText(0,0,"100")
EndIf
GraphicsWindow.Height=275
GraphicsWindow.Width=450
GraphicsWindow.BrushColor="#003580
GraphicsWindow.FillRectangle(0,100,450,75)
GraphicsWindow.FillRectangle(125,0,75,275)

```

Try it at SmallBasic.com! *Requires IE/Silverlight*

### Output

Shown after the Finland's 100th independence day.
> 1 votes

# Answer
the previously made code has been golfed down to the following:

# HTML, CSS and JavaScript, 1599 bytes

```
var d1=new Date(1917,11,6);
var d2=new Date();
var difference = d2.getFullYear()-d1.getFullYear();
if(difference===100 && d2.getDate()===d1.getDate() && d2.getMonth()===d1.getMonth()) {
 document.getElementById("bottom-right").innerHTML=d2.getFullYear()-d1.getFullYear();
}
```

```
#flag{
background-color: #FFF;
width: 540px;
height: 330px;
border: 6px solid gray;
margin: 10% auto;
}
.surround{
background-color: #003580;
width: 90px;
height: 120px;
margin: 0px 300px 0px 150px;
}
.middle{
background-color: rgb(0, 53, 128);
width: 540px;
height: 90px;
}
```

```
<head>
<title>Happy Birthday, Finland</title>
<link rel="stylesheet" type="text/css" href="decor.css">
</head>
<body>
<div id="flag"><div class="surround"></div><div class="middle"></div><div class="surround"></div></div>
<script type="text/javascript" src="date.js"></script>
</body>
```
> 0 votes

# Answer
## JavaScript ES6, 532 bytes

Decided to try using a Base64 image to see how short I could get it. Not a winner, but interesting nonetheless.

```
document.write(`${Date.now()>1512525600000?'<i style=position:fixed>100</i>':''}<img src=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAALQAAABuAQMAAAC0pqs4AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABlBMVEX///8ANYAaS5LoAAAAAWJLR0QB/wIt3gAAAAd0SU1FB+EMBRcAAPqLykEAAAAxSURBVEjHY2AAA/v///8zYAGj4qPio+KDWfw/VvBhVHxUfEiKD7b8NSo+Kj4qTrQ4AHKtsHq12fKCAAAAJXRFWHRkYXRlOmNyZWF0ZQAyMDE3LTEyLTA1VDIzOjAwOjAwKzAxOjAwkDJOKAAAACV0RVh0ZGF0ZTptb2RpZnkAMjAxNy0xMi0wNVQyMzowMDowMCswMTowMOFv9pQAAAAASUVORK5CYI>`)
```
> 0 votes

# Answer
# HTML + JavaScript, 247 bytes

```
<table cellspacing=0 cellpadding=0><tr height=40><td width=50><td width=30 bgcolor=003580><td width=100><tr height=30><td colspan=3 bgcolor=003580><tr height=40><td><td bgcolor=003580><td><script>Date.now()>15125112e5&&document.write(100)</script>
```
> 0 votes

# Answer
## Asymptote, ~~68~~ 90 bytes

Run on http://asymptote.ualberta.ca/

*Asymptote 90 bytes* (add the number 105, not 100 ^^)

```
draw((0,0)--(180,0)^^(65,-50)--(65,50),rgb(0,53,128)+30+linecap(0));label("105",(130,35));

```

*Asymptote 68 bytes*

```
draw((0,0)--(180,0)^^(65,-50)--(65,50),rgb(0,53,128)+30+linecap(0));

```
> 0 votes

# Answer
# C (GCC), 236 bytes

```
i=-55;main(j,z,t){t=time(0)>1512521999;for(write(1,"P6 180 110 255 ",15);i<56;i-=~!i)for(j=-65;j<116;j-=~!j)write(1,((z=i*i+(j-22)*(j-22))<80&z>48|(z=i*i+j*j)<80&z>48|(abs(j+16)<2)&(abs(i)<9))&t?"\0\0":abs(i*i<j*j?i:j)>15?"ÿÿÿ":" 5€",3);}

```

Adaptation of my solution of the related Icelandic challenge.

Set encoding to `ANSI`, so each character corresponds to a single byte, and replace `\0` with a `NUL` byte. Outputs to `stdout` a PPM image.

---
> 0 votes

---
Tags: code-golf, graphical-output, date
---


title: Sum of consecutive nth powers

text:
# Question
Title: Sum of consecutive nth powers
Related.

Given a positive integer \\$n\\$, output all integers \\$b\\$ (such that \\$1\<b\<n-1\\$) where \\$n\\$ can be written as the sum of any number of consecutive powers of \\$b\\$.

**Example:**

Let's say \\$n=39\\$.

\\$3^1+3^2+3^3\\$
\\$= 3 + 9 + 27\\$
\\$= 39\\$

This does not work for any other \\$b\\$, so our output is `[3]`.

**Test cases up to \\$n=50\\$:**

```
1: []
2: []
3: []
4: [2]
5: []
6: [2]
7: [2]
8: [2]
9: [3]
10: []
11: []
12: [2,3]
13: [3]
14: [2]
15: [2]
16: [2,4]
17: []
18: []
19: []
20: [4]
21: [4]
22: []
23: []
24: [2]
25: [5]
26: []
27: [3]
28: [2]
29: []
30: [2,5]
31: [2,5]
32: [2]
33: []
34: []
35: []
36: [3,6]
37: []
38: []
39: [3]
40: [3]
41: []
42: [6]
43: [6]
44: []
45: []
46: []
47: []
48: [2]
49: [7]
50: []

```

**Clarifications:**

# Answer
# Nekomata, 9 bytes

```
←ᶠ{ᵈqEů∑=

```

Attempt This Online!

```
←ᶠ{ᵈqEů∑=
←           Decrement
 ᶠ{         Filter the range [0, n) by:
   ᵈq           Find any subsequence of the range [0, input)
     E          Power
      ů         Check that it does not contain duplicates
                    so that the base is not 1
       ∑        Sum
        =       Check that it is equal to the input

```

---

# Nekomata, 10 bytes

```
←ᶠ{1>B:o±=

```

Attempt This Online!

A port of @Jonathan Allan's Jelly answer.

```
←ᶠ{1>B:o±=
←           Decrement
 ᶠ{         Filter the range [0, n) by:
   1>           Check that it is greater than 1
     B          Convert the input to that base
      :  =      Check that it is invariant under:
       o          Sort
        ±         Sign

```

Now I regret supporting converting to base 1, otherwise that `1>` could be omitted.
> 4 votes

# Answer
# JavaScript (V8), 62 bytes

Prints the results.

```
n=>{for(b=1;i=++b<n-1;k||print(b))for(k=n;k%b?i--:k/=b;)k-=!i}

```

Try it online!

### Algorithm

Given the input \\$n\\$ and for each \\$b\in\[2,n-2\]\\$:

1. we do \\$n\gets n/b\\$ as long as \\$n\equiv 0\pmod b\\$
2. we do \\$n\gets (n-1)/b\\$ as long as \\$n-1\equiv 0\pmod b\\$

If we end up with \\$n=0\\$, then \\$b\\$ is a solution.

### Explanation

If \\$n\\$ is of the form \\$b^p+b^{p+1}+\dots+b^{p+q}\\$, the first step will normalize it to:

$$b^0+b^1+\dots+b^q$$

and each iteration of the second step will remove the most significant term ...

$$b^0+b^1+\dots+b^{q-1}$$

... until it's eventually reduced to \\$0\\$.

---

### C (gcc), 79 bytes

Essentially the same code.

```
b,i,k;f(n){for(b=1;i=++b<n-1;k||printf("%d ",b))for(k=n;k%b?i--:(k/=b);)k-=!i;}

```

Try it online!

I wish it could be rearranged to get rid of `:(k/=b)`. The obvious way is `k%b<1?k/=b:i--`, but that's just as long.
> 10 votes

# Answer
# Python, 82 bytes

*-1 byte, thanks to xnor*
*-1 byte, thanks to Arnauld*

```
lambda n:[b for b in range(2,n-1)for i in range(n*n)if~-b*n==b**(i%n+1)-b**(i//n)]

```

Attempt This Online!

Uses the equation \\$\sum\_{k=i}^{j}b^k = \frac{b^{j+1}-b^i}{b-1}\\$
> 7 votes

# Answer
# Vyxal, 73 bitsv2, 9.125 bytes

```
⇩Ḣ'?ʀeÞSṠ?c

```

Try it Online!

Formulas? No we do things brute force around here.

## Explained

```
⇩Ḣ'?ʀeÞSṠ?c
⇩Ḣ'          # Keep all from the range [2, n - 2] where:
      ÞSṠ    #   Sums of sublists of
   ?ʀe       #   The number raised to each number in the range [0, input]
         ?c  #   Contains the input

```

Created with the help of Luminespire.
> 7 votes

# Answer
# Charcoal, ~~24~~ 20 bytes

```
ＮθＩΦ…²⊖θ¬⊙⪪⍘θι0⁻λＩ¬μ

```

Try it online! Link is to verbose version of code. Explanation: When converted to base `b`, `n` has to have the form `1+0*`, thus when split on `0` the first part can only contain `1`s and the other parts must be empty, although the code "permits" `0`s.

```
Ｎθ                      Input `n` as a number
    …                   Range from
     ²                  Literal integer `2` to
       θ                Input `n`
      ⊖                 Decremented
   Φ                    Filtered where
            θ           Input `n`
           ⍘            Converted to base
             ι          Current value
          ⪪             Split on
              0         Literal string `0`
        ¬⊙              All parts satisfy
                λ       Current part
               ⁻        Only contains occurrences of
                   μ    Inner index
                  ¬     Logical Not
                 Ｉ      Cast to string
                        Implicitly print

```
> 7 votes

# Answer
# Jelly, 10 bytes

```
½Ḋbt0ỊƑɗ@Ƈ

```

A monadic Link that accepts a positive integer and yields a list of all valid integer bases.

**Try it online!**

### How?

A base, \\$b\\$, works for \\$n\\$ when \\$n\\$ converted to base \\$b\\$ is a run of ones optionally followed by a run of zeros.

No \\$b \> \sqrt{n}\\$ can work since the \\$b^2\\$ term breaks the bank on its own and the \\$b^1\\$ and \\$b^0+b^1\\$ solutions are the excluded cases \\$b\ge n-1\\$.

```
½Ḋbt0ỊƑɗ@Ƈ - Link: positive integer, n
½          - square-root {n}
 Ḋ         - dequeue -> B = [2,3,4,...,floor(sqrt(n))]
         Ƈ - keep those {b in B} for which:
       ɗ@  -   last three links as a dyad with swapped arguments - f(n, b):
  b        -     convert {n} to base {b}
   t0      -     trim zeros (e.g. [4,0,1,0,0,0] -> [4,0,1])
      Ƒ    -     is invariant under?:
     Ị     -       insignificant? (abs(digit)<=1 vectorised)

```
> 7 votes

# Answer
# Ruby, ~~55~~ 56 bytes

```
->n{(2..n-2).select{|x|/^[0_]*(1_)+1$/=~n.digits(x)*?_}}

```

Try it online!

If a number `n` is the sum of consecutive powers of `x`, then its representation is base `x` is a sequence of `1`s followed by any number of zeroes.
> 5 votes

# Answer
# Haskell, 54 bytes

```
f n|r<-[0..n]=[i|i<-[2..n-2],a<-r,b<-r,n*i-n==i^a-i^b]

```

Try it online!
> 5 votes

# Answer
# K (ngn/k), ~~28~~ 26 bytes

```
{2+&x{i~!#i:&y\x}'-1_2_!x}

```

-2 thanks to @coltim

Try it online!
> 5 votes

# Answer
# Haskell, 74 bytes

```
0#i=[]
n#i=mod n i:div n i#i
f n=[i|i<-[2..n-2],all(==1)$snd$span(<1)$n#i]

```

Attempt This Online!
> 4 votes

# Answer
# Wolfram Language (Mathematica), 58 bytes

```
Select[r=Range[0,#-2],Tr/@Subsequences[#^r]&/*MemberQ[#]]&

```

Try it online!

-2 bytes from @att
> 4 votes

# Answer
# 05AB1E, ~~12~~ 11 bytes

```
tL¦ʒIÝmŒOIå

```

-1 byte thanks to *@MTN* by porting `tL¦` from *@JonathanAllan*'s Jelly answer.

Try it online or verify all test cases.

**Explanation:**

```
t        # Get the square-root of the (implicit) input-integer
 L       # Pop and push a list in the range [1,floor(sqrt(input))]
  ¦      # Remove the leading 1 to make the range [2,floor(sqrt(input))]
ʒ        # Filter this list by:
 IÝ      #  Push a list in the range [0,input]
   m     #  Take the current integer to the power of each of these values
    Œ    #  Get all sublists of this list
     O   #  Sum each inner sublist
      Iå #  Check whether the input is in this list of sums
         # (after which the filtered list is output implicitly as result)

```
> 4 votes

# Answer
# Perl 5, 88 bytes

```
sub{grep{$x=$_;join('+',map$x**$_,0..$n)=~/\b.+\b(??{$n-eval$&?$;:""})/}2..sqrt($n=pop)}

```

Try it online!
> 3 votes

# Answer
# Scala 3, 85 bytes

```
n=>for{b<-2 to n-2;i<-0 to n*n-1;if(b-1)*n==math.pow(b,i%n+1)-math.pow(b,i/n)}yield b

```

Attempt This Online!

---

Uses the equation \\$\sum\limits\_{k=i}^{j}b^k = \frac{b^{j+1}-b^i}{b-1}\\$
> 3 votes

---
Tags: code-golf, math, integer
---


title: Displaying n with n

text:
# Question
Title: Displaying n with n
## What I want:

Quite simply, I want a text based display, that asks for an input, `n`, then shows that value on the display! But there's a catch. Each of the 'true' 'pixels' (the ones filled in) has to be represented by that number `n`..

## Example :

You are given an input `n`. You can assume `n` will be a single digit

```
Input: 0
Output:
000
0 0
0 0
0 0
000

Input: 1
Output:
  1
  1
  1
  1
  1

Input: 2
Output:
222
  2
222
2
222

Input: 3
Output:
333
  3
333
  3
333

Input: 4
Output:
4 4
4 4
444
  4
  4

Input: 5
Output:
555
5
555
  5
555

Input: 6
Output:
666
6
666
6 6
666

Input: 7
Output:
777
  7
  7
  7
  7

Input: 8
Output:
888
8 8
888
8 8
888

Input: 9
Output:
999
9 9
999
  9
999

```

# Challenge:

Do the above it in as few bytes as possible.

I will only accept answers that meet all requirements.

**Surrounding whitespace is optional,** as long as the digit is displayed properly.

Also, \<75 bytes is a vote from me, the lowest accept, but I could always change the accepted answer, so don't be discouraged to answer.

# Answer
> 8 votes
# SOGL V0.12, 30 bytes

```
■'τč▲Β►║⁰ΡāQšJ┘tXdnοO¹‘'¹n.w3n

```

Try it Here! The compressed string `■'τč▲Β►║⁰ΡāQšJ┘tXdnοO¹‘` is

```
  ŗ  ŗ  ŗ  ŗ  ŗŗŗŗ  ŗŗŗŗŗ  ŗŗŗŗŗŗ  ŗŗŗŗ  ŗŗŗŗŗ ŗŗ ŗŗŗŗ  ŗ  ŗŗŗŗŗ  ŗŗŗ  ŗŗŗŗŗŗŗŗ  ŗŗŗŗ ŗŗŗŗŗŗŗ  ŗ  ŗ  ŗ  ŗŗŗŗŗ ŗŗŗŗŗ ŗŗŗŗŗŗŗŗ ŗŗŗŗ  ŗŗŗŗŗŗŗŗ ŗŗ ŗŗ ŗŗŗŗ

```

which is (starting with 1, ending with 0) the numbers, line by line, number to number. The rest

```
...‘             push the compressed string, replacing the ŗs with pop - the input
    '¹n          split into chunks of 15
       .w        push the (1-indexed, wrapping) input-th item of that array
             3n  split into chunks of 3
                 implicitly output the array, line by line

```

# Answer
> 14 votes
## JavaScript (ES6), 88 bytes

```
f=
n=>`019
2 3
459
6 7
889`.replace(/\d/g,c=>[2,18,142,96,130,131,698,4,146][c]>>n&1?` `:n)
```

```
<input type=number min=0 max=9 oninput=o.textContent=f(this.value)><pre id=o>
```

The numbers encode which squares contain spaces for a given digit e.g. the bottom left corner has a value of 146 because the 1, 4 and 7 don't use it and 146 = 2¹ + 2⁴ + 2⁷.

# Answer
> 11 votes
# 05AB1E, ~~40~~ ~~39~~ 38 bytes

```
•Y¤ŸèK'¦ú’ò™^N•4B5ô¹èvð¹«5714yè8+b¦Sè,

```

Try it online!

**Explanation**

```
•Y¤ŸèK'¦ú’ò™^N•            # the compressed string "318975565561233953387608032537"

4B                         # convert to base-4
  5ô                       # split into strings of size 5
    ¹è                     # get the string at index <input>
      v                    # for each digit y in string
          5714yè           # get the digit in 5714 at index y
                8+         # add 8
                  b        # convert to binary
                   ¦       # remove the leading 1
       ð¹«          Sè     # with each digit in the binary number,
                           # index into the string " <input>"
                      ,    # print with newline

```

# Answer
> 11 votes
# Japt, 43 bytes

```
"Ýûÿ©ÿßY÷ß"®c s4Ã¤ëAU ¬£2839¤ë4XÃ·d0S1U

```

Contains some unprintables. Try it online!

Tallies: 13 bytes of compressed data, 9 bytes to decompress it, and 21 bytes to form the output.

### Explanation

Ungolfed code:

```
"Ýûÿ©ÿßY÷ß"®   c s4Ã ¤  ëAU ¬ £  2839¤  ë4XÃ ·  d0S1U
"Ýûÿ©ÿßY÷ß"mZ{Zc s4} s2 ëAU q mX{2839s2 ë4X} qR d0S1U

```

There are exactly 4 different row possibilities: (`#` represents a digit)

```
#
  #
# #
###

```

Thus, each number can be stored as a set of five base-4 digits. Since each number can be then stored in 10 bits, the total is 100 bits, which corresponds to 13 bytes. I'll skip the compression process and instead explain the decompression.

```
mZ{Zc s4}

mZ{     }  // Replace each character Z in the compressed string with the following:
   Zc      //   Take the char-code of Z.
      s4   //   Convert to a base-4 string.

```

After decompression, the 13-byte compressed string looks like this:

```
3131332333332111200122213333313321011121213133133133

```

Note that this would fail if any of the 4-digit runs started with `0`, as the leading zeroes would be left off when `s4` is run. We can fix this by having `0` represent `#`, which only appears three times, and none of those fall at the start of a 4-digit run.

```
s2         // Slice off the first two chars of the result.

```

Okay, so in order to get our 50-digit string to compress nicely in chunks of 4, we had to add two extra digits. Adding them to the beginning of the string means we can chop them off with the one-byter `¤`.

```
ëAU        // Take every 10th (A) char in this string, starting at index <input> (U).

```

Embarrassingly, Japt lacks a built-in for splitting a string into slices of length X. It does have a built-in for getting every Xth char, however, so we can store all the data by encoding all of the top rows first, then all of the second rows, etc.

So now we have the 5-digit string encoding the digit we want to create, e.g. `32223` for `0`.

```
q mX{2839s2 ë4X} qR
q                    // Split the resulting string into chars.
  mX{          }     // Replace each char X with the result of this function:
     2839s2          //   Convert the magic number 2839 to a binary string.
            ë4X      //   Take every 4th char of this string, starting at index X.
                 qR  // Join the result with newlines.

```

To explain the magic number, refer back to the four distinct rows. If you replace `#` with `1` and  with `0`, you get

```
100
001
101
111

```

Transposing this and then joining into a single string gives us `101100010111`. Convert to decimal and, voilà, you have 2839. Reversing the process maps the digits `0123` into the four binary rows shown above.

Almost done! Now all that's left to do is add in the spaces and digits:

```
d0S1U      // In the resulting string, replace 0 with " " (S) and 1 with <input> (U).

```

And presto, implicit output takes care of the rest. I'm sorry this explanation is so long, but I don't see any real way to golf it without making it less understandable (if it is understandable...)

# Answer
> 9 votes
## JavaScript (ES6), ~~115~~ 111 bytes

Takes input as a string.

```
n=>'02468'.replace(/./g,c=>(n+n+n+`   ${n} `+n).substr([126,341,36,68,327.5,66,98,340,102,70][n]*4>>c&6,3)+`
`)

```

### How it works

**Pattern encoding**

The four distinct patterns `"XXX"`, `"X.."`, `"..X"` and `"X.X"` can be compressed as `"XXX...X.X"` and extracted this way:

```
XXX...X.X
^^^        --> XXX  (id = 0 / pointer = 0)
  ^^^      --> X..  (id = 1 / pointer = 2)
    ^^^    --> ..X  (id = 2 / pointer = 4)
      ^^^  --> X.X  (id = 3 / pointer = 6)

```

By substituting the input digit `n` for `"X"` and using actual spaces, this gives the expression:

```
n+n+n+`   ${n} `+n

```

**Digit encoding**

Using the pattern identifiers defined above, each digit can be represented by a 5 * 2 = 10-bit quantity.

For instance:

```
XXX  -->  0 *   1 =   0
X.X  -->  3 *   4 =  12
XXX  -->  0 *  16 =   0
..X  -->  2 *  64 = 128
XXX  -->  0 * 256 =   0
                    ---
                    140

```

The complete list is:

```
[252, 682, 72, 136, 655, 132, 196, 680, 204, 140]

```

However, dividing these values by 2 allows to save two bytes. So instead we store:

```
[126, 341, 36, 68, 327.5, 66, 98, 340, 102, 70]

```

### Demo

```
let f =

n=>'02468'.replace(/./g,c=>(n+n+n+`   ${n} `+n).substr([126,341,36,68,327.5,66,98,340,102,70][n]*4>>c&6,3)+`
`)

console.log(f('0'))
console.log(f('1'))
console.log(f('2'))
console.log(f('3'))
console.log(f('4'))
console.log(f('5'))
console.log(f('6'))
console.log(f('7'))
console.log(f('8'))
console.log(f('9'))
```

# Answer
> 6 votes
# Bash + GNU utils, 114

* 2 bytes saved thanks to @SophiaLechner

There are probably some more opportunities for compression here, but here's a start:

```
dc<<<4o16iEAC00CDF33AC373DEF00EEFB3p|fold -5|sed "$[$1+1]!d
s/0/  x\n/g
s/1/x\n/g
s/2/x x\n/g
s/3/xxx\n/g
y/x/$1/"

```

### Explanation

Each row of of every digit is one of these four patterns:

```
  x
x
x x
xxx

```

By labeling these 0-3, each digit can be represented by 5 base-4 digits. E.g. 0 would be `32223`, and the full list of digits is encoded in base-4 as `32223000003031330303223003130331323300003232332303`. This encoded in hex as `EAC00CDF33AC373DEF00EEFB3`.

* `dc` converts hex `EAC00CDF33AC373DEF00EEFB3` to base-4.
* `fold` puts 5 base-4 digits on each line
* `sed`:
    + deletes all input lines apart from line number n+1 (sed 1-indexes lines)
    + translates the base-4 digits to the pattern (of `x`es) for each line of the given digit, along with a newline for the end of each row
    + transliterates the `x`es to digit n.

Try it online.

# Answer
> 5 votes
# MATL, ~~45~~ 43 bytes

```
'V~4;LR`I-D2q (z%eI)P-nc'F TFZa15eiZ)5eGV*c

```

Try it online!

### Explanation

```
'V~4;LR`I-D2q (z%eI)P-nc' % Compressed string using printable ASCII except '
F TFZa                    % Decompress (change of base) into alphabet [1 0]
15e                       % Reshape into 15-row matrix. Each column contains the
                          % art for one digit, packed in column-major order
iZ)                       % Take input number and pick the corresponding column.
                          % Indexing is 1-based and modular, so 0 is at the end
5e                        % Reshape into a 5-row matrix. This already looks like
                          % the number, with active pixels as 1 and inactive as 0
GV                        % Push input number again. Convert to string, of one char
*                         % Multiply, element-wise. The previous char is
                          % interpreted as its ASCII code. This changes 1 into the
                          % ASCII code of the input digit, and leaves 0 as is
c                         % Convert to char. Implicitly display. Char 0 is shown as
                          % a space

```

# Answer
> 3 votes
# Retina, ~~166~~ ~~164~~ 163 bytes

Two spaces on the third line from the bottom

```
0
0addda
d
0 0
1
1b1b1b1b1b1
2
2ab2a2b222
3
3ab3ab3a
4
44 44 4ab4b4
5
55ab555b5a
6
66ab6a 6a
7
7ab7b7b7b7
8
88a 8a8 8a
9
99a 9ab9a
(\d)a
$1$1$1$1
^.

b

.{3}
$+¶

```

Try it Online!

An improved version of @Okx's solution

# Answer
> 2 votes
# Pyth 82 85 91 100 bytes

```
Km?dC+48Q\ m.&C@"w$kn<^_d\x7f~"Qdj1906486293414135453684485070928 128V5p.)Kp.)K.)K

```

A lot of golfing probably possible, my first challenge.

# Answer
> 2 votes
## Batch File, 8 + 184 bytes

Here's my obligatory batch solution. Unfortunately the standard method of accomplishing this is over 300 bytes in batch, so we resort to much cheaper tactics.

```
@type %1

```

---

In the current directory, I have 10 files set up, named from 0 to 9. In each of these is the respective 5x3 grid of pixels. For example:

The byte counts for these are:

```
19 0
19 1
17 2
19 3
19 4
17 5
17 6
19 7
19 8
19 9
Total - 184

```

***Still beat Java.***

# Answer
> 1 votes
# Retina, 190 bytes

```
0
000¶aaa000
a
0 0¶
1
aaaaa
a
b1¶
2
ab2¶a2¶a
a
222¶
3
ab3¶ab3¶a
a
333¶
4
4 4¶4 4¶444¶b4¶b4
5
a5b¶ab5¶a
a
555¶
6
a6¶a6 6¶a
a
666¶
7
777aaaa
a
¶b7
8
a8 8¶a8 8¶a
a
888¶
9
a9 9¶ab9¶a
a
999¶
b

```

There are two spaces on the last line ~~but SE doesn't want to render it :/~~ Fixed!

Try it online!

# Answer
> 1 votes
# PowerShell,159 135 128 118 bytes

```
param($n);0..4|%{("$n$n$n","$n $n","  $n","$n  ")['01110333330203002020110220302003010022220101001020'[$_+($n*5)]-48]}

```

Current answer: removed extraneous variable naming

Try it online!

I'll have to see if I can get some tricks from the other answers :P

**EDIT** Getting smarter with calling the mega string

**EDIT2** Switched to using a string of numbers to index into `$a` to save 7 bytes. Although I liked my previous dynamic variable name calls in the below code (135 bytes)

```
param($n);$a="$n$n$n";$b="$n $n";$c="  $n";$d="$n  ";$r="abbbadddddacadaacacabbaccadacaadabaaccccababaabaca";0..4|%{gv $r[$_+($n*5)]-v}

```

# Answer
> 1 votes
# PHP, 115 Bytes

```
for(;$i<5;)echo strtr(sprintf("%03b\n","1754"[[425,0,465,273,26,285,413,1,409,281][$argn]/4**$i++%4]),[" ",$argn]);

```

Try it online!

Expanded

```
for(;$i<5;)
  echo strtr(
    sprintf("%03b\n",  # make a binary
      "1754"[[425,0,465,273,26,285,413,1,409,281][$argn]/4**$i++%4])
    ,[" ",$argn]); # replace 0 with space and 1 with the input

```

Encoding Try it online!

# Answer
> 1 votes
# Ruby, 94 bytes

```
->n{20.times{|i|print i%4>2?$/:[" ",n]["_Q_@@_]UWUU_GD_WU]_U]AA__U_WU_"[n*3+i%4].ord>>i/4&1]}}

```

**Ungolfed in test program**

```
f=->n{
  20.times{|i|                           #4 characters * 5 rows = 20
    print i%4>2?$/:                      #If i%4=3 print a newline else
    [" ",n][                             #either a space if the expression below is 0 or the digit n if 1.
      "_Q_@@_]UWUU_GD_WU]_U]AA__U_WU_"[  #bitmap data for digits, one character for each column
        n*3+i%4].ord>>i/4&1              #Select the correct character for the column, convert to ascii code,
    ]                                    #rightshift to find the correct bit for the row,
  }                                      #use & to isolate the bit: 0 or 1
}

f[gets.to_i]

```

# Answer
> 1 votes
# PowerShell, ~~126~~ ~~120~~ ~~113~~ ~~109~~ 101

```
$n="$args"
-split'ϽϭϿ·ͱ Ο·ͽͼϿ·Ņ ϻ·ͭͭϿ'|%{-join($_[0..2]|%{"$n·"[!($_-band1-shl$n)]})}

```

Unicode is fun. Characters are also way shorter than numbers. Above code contains U+0000 twice, thus cannot be copied directly (works fine in a file, though). The following code can be copied:

```
$n="$args"
-split"ϽϭϿ ͱ`0Ο ͽͼϿ Ņ`0ϻ ͭͭϿ"|%{-join($_[0..2]|%{"$n "[!($_-band1-shl$n)]})}

```

We lose three bytes because we need the UTF-8 signature at the start. Otherwise the string won't work.

# Answer
> 1 votes
# Retina, 125 bytes

```
.
A$&¶B$&¶C$&¶D$&¶E$&
([ACE][235689]|A0|E0|C4|A7)(?<=(.))
$2$2$2
(B[0489]|D[068]|A4|C0)(?<=(.))
$2 $2
D2
2
B5
5
B6
6
[A-E]

```

Try it online! (Delete test suite in header to test individual input digits.) Last line contains two spaces.

# Answer
> 1 votes
# Python 2, ~~174~~ 125 bytes

```
lambda n:'\n'.join('xxx  x x'[int(i):][:3]for i in oct(0x3028000adba93b6b0000c0ad36ebac30180c0)[:-1][n::10]).replace('x',`n`)

```

Try it online!

# Answer
> 1 votes
# Java 8, ~~278~~ ~~214~~ ~~210~~ 204 bytes

```
n->("A"+n+"\nB"+n+"\nC"+n+"\nD"+n+"\nE"+n).replaceAll("([ACE][235689]|A0|E0|C4|A7)(?<=(.))","$2$2$2").replaceAll("(B[0489]|D[068]|A4|C0)(?<=(.))","$2 $2").replaceAll("D2|B5|B6",n).replaceAll("[A-E]","  ")

```

Port of *@Neil*'s Retina answer. Takes the input as a `String`.

Try it here.

# Answer
> 0 votes
# Charcoal, ~~61~~ ~~38~~ 33 bytes

```
Ｅ§⪪”{⊞¶↙⬤\→(Ｂ⊘K→υ^⎇\`｜;ε”⁵Ｎ⮌⍘Ｉι⁺ θ

```

Try it online! Link is to verbose version of code. Explanation:

```
   ”...”            Compressed data string
  ⪪     ⁵           Split into groups of 5 digits
 §                  Indexed by
         Ｎ          First input as an integer
Ｅ                   Map over digits
             ι      Current digit
            Ｉ       Cast to integer
           ⍘        Converted to custom base
              ⁺ θ   Space concatenated with input digit
          ⮌         Reversed
                    Implicitly print

```

A generic port is a bit boring, so here's a more idiomatic 61-byte answer:

```
ＧＨ✳✳§⟦⟦↑L↓¬⟧⟦↓↓⟧⟦T↓→⟧⟦T→¬⟧⟦↑↑¬↑⟧⟦←↓T⟧⟦T↑L⟧⟦→↓↓⟧⟦+L↓⟧⟦+↓T⟧⟧Ｎ³θ

```

Try it online! No verbose version as the deverbosifier doesn't understand lists of directions or even multidirectionals inside ordinary polygons. Explanation:

```
     ⟦...⟧      Array of paths, see below
          Ｎ     Input as an integer
    §           Index into the array
  ✳✳            Treat the element as direction data
           ³    Length of each segment (including 1 character overlap)
            θ   Draw using the input character
ＧＨ              Draw a path

```

Each path is specified using a list of directions (`←↑→↓`). Four usable shortcuts save bytes: `L` represents `↑→`, `¬` represents `↓←`, `T` represents `→↓←` while `+` represents `→↓←↑`, although at least one arrow must remain for the list to be recognised as a direction list (so for instance `TT` cannot be used for `3`).

60 bytes using the newer version of Charcoal available on ATO:

```
ＧＨ✳✳§⟦⟦⌈¬↑↑⟧⟦↓↓⟧⟦T↓→⟧⟦T→¬⟧⟦↑↑¬↑⟧⟦←↓T⟧⟦+↑→⟧⟦⌈↓⟧⟦+↑⌈⟧⟦+↓T⟧⟧Ｎ³θ

```

Attempt This Online! Link is to verbose version of code. Explanation: The order in which multidirectionals execute changed which means that `7` can now be drawn using a multidirectional and an arrow instead of three arrows. Some of the other digits have had to have their multidirectionals tweaked but this was possible without changing the length of the code.

# Answer
> 0 votes
# Jelly, ~~35~~ 32 bytes

```
Ṿ⁶,“SÐ~ẈoI9Ẇ¦Y./,0&Ƥɓ€ọ’ṃs15ị@s3

```

Try it online! or see them all.

Same as dzaima's method.

# Answer
> 0 votes
# Perl 5 `-Mbigint -pa`, 101 bytes

```
$_=sprintf"%16b",0xf79ef7dee492f3def39eb792e79ee7ce4924f6de>>16*$_&65535;eval"y/01/ @F/";s/...\K/\n/g

```

Try it online!

# Answer
> 0 votes
# Python 3, 119 bytes

```
lambda n:(3*f"%s%s{n}\n%s %s\n")[:30]%(*[n if i//(2**n)%2else" "for i in[1021,1005,881,927,893,892,325,1019,877,877]],)

```

Try it online!

Each 'pixel' is represented as an integer where each power of two indicates whether the pixel is solid. This takes advantage of the fact that the three right-hand corners are always the digit.

# Answer
> 0 votes
# Befunge, ~~192~~ 174 bytes

```
3040040403333004010030103304403030010302222204440&:09p5*>:  #v_v
   9g86*+:00p:10p:20p:01p:12p:23p:04p24p 6v             ^-1$\< >
   ,+55,g\2,g\1:,g\0:\_@#:-1p31p30:p41:*84<$

```

Try it online!

First stab was ~360 bytes doing if/else & pushing characters to stack. Which was devoting 150 characters to encoding numbers. So instead encode characters as 5 numbers based on each line. Then pop 5x input to have top 5 stack elements be desired character. 2nd line sets up line pieces with correct characters in top left 3x5 of memory

# Answer
> -3 votes
# JavaScript (ES8), 87 bytes

```
n=>`019
2 3
459
6 7
889`.replace(/\d/g,c=>[2,18,142,96,130,131,698,4,146][c]>>n&1?' ':n)

```

---
Tags: code-golf, ascii-art, kolmogorov-complexity
---


title: Add two really big numbers

text:
# Question
Title: Add two really big numbers
## Preamble

We've already proven we're good at adding two numbers, but many solutions only operate on tiny numbers like 2³²-1, honestly we can do a lot better.

## The Challenge

Given two unsigned, non-negative integers, add them together and return the output.

Input may be taken in any convenient format (String, Array of bytes/characters, BigInteger, etc.), and output may be in any convenient format as well. Inputs may optionally be padded with any character of choice to any length of choice.

Output must support at minimum all numbers in the range of \[0,10²⁵⁶), Inputs will always be in this range as well.

## Test Cases

```
1168 + 0112 = 1280
23101333 + 01858948 = 24960281
242942454044 + 167399412843 = 410341866887
9398246489431885 + 9300974969097437 = 18699221458529322
83508256200399982092 + 74143141689424507179 = 157651397889824489271
173163993911325730809741 + 291008926332631922055629 = 464172920243957652865370

```

## Rules

* Standard IO Applies
* Standard Loopholes Apply
* You may **not** output as Scientific Notation. All digits must be included in the output.
* Solutions do **not** need to finish in any reasonable time, they only must provably work.
* Use of built-in BigInteger implementations is allowed, though I encourage you to include a non-built-in solution.
* This is so fewest bytes wins!
* I/O may not be taken as Unary.
* Have Fun!

# Answer
> 10 votes
# Trivial Built-in Answers

For languages where bignum addition is already supported.

## 05AB1E, Brachylog, Factor, , Jelly, Julia, Nekomata, RProgN 2, Vyxal, 1 byte

```
+

```

Try it online! (05AB1E)

Try it online! (Brachylog)

Try it online! (Factor)

Attempt This Online! (J)

Try it online! (Jelly)

Try it online! (Julia)

Attempt This Online! (Nekomata)

Try it online! (RProgN 2)

Try it Online! (Vyxal)

---

## Haskell, Python, Raku, 3 bytes

```
sum

```

Attempt This Online! (Haskell)

Attempt This Online! (Python)

Attempt This Online! (Raku)

Takes input as a list.

---

## Charcoal, 2 bytes

```
Ｉ⁺

```

Try it online! Requires input in JSON format. 4 bytes for string input:

```
Ｉ⁺ＮＮ

```

Try it online!

---

## Java, 14 bytes

```
a->b->a.add(b)

```

I/O as `java.math.BigInteger`s.

Try it online.

---

## JavaScript (ES11), 9 bytes

With BigInts as I/O.

```
a=>b=>a+b

```

Try it online!

---

## PARI/GP, 9 bytes

```
a->b->a+b

```

Attempt This Online!

---

## Ruby, 8 bytes

```
proc &:+

```

Attempt This Online!

# Answer
> 8 votes
# 05AB1E, ~~13~~ 9 bytes

```
Dv+T‰Áø`À

```

Try it online!

No bigints. Takes both inputs as a reversed list of digits, padded to at least the length of the output, and outputs in the same way.

Uses `a + b = (list(a)+list(b))%10 + right_rotate((list(a)+list(b))//10)`. Once we do that length(output) times the second addend will become zero.

## Explanation

```
      # implicit input a, b
D     # duplicate b, stack is a,b,b
v     # for x in b (x isn't used)
 +    # add a+b digit-wise
 T    # push 10
 ‰    # divmod, so we now have a list of ((a[i]+b[i])//10, (a[i]+b[i])%10)
 Á    # rotate right
 ø    # transpose
 `    # dump, the stack has right_rotate((a[i]+b[i])//10), right_rotate((a[i]+b[i])%10)
 À    # left rotate
      # stack is right_rotate((a[i]+b[i])//10), (a[i]+b[i])%10
# implicit output

```

# Answer
> 7 votes
# K (ngn/k), 13 bytes

```
10!(_0.1/,)\+

```

Try it online!

Takes two lists of digits in reverse order padded to an equal length that is at least as long as the result.

```
10!(_0.1/,)\+
            +   Add two numbers digit-by-digit
   (      )\    Handle carry using scan:
                  left = 10 * carry + digit value, right = next digit value
    _0.1/,        add carry to the next digit
10!             Remove carry information

```

# Answer
> 6 votes
# TypeScript's Type System, ~~211~~ 193 bytes

```
//@ts-ignore
type F<A,C=[]>=A extends[[...infer G,infer X],[...infer H,infer Y]]?[...X,...Y,...C]extends[1,1,1,1,1,1,1,1,1,1,...infer R]?[...F<[G,H],[1]>,R]:[...F<[G,H],[]>,[...X,...Y,...C]]:[]

```

Try it at the TypeScript Playground!

This is a generic type `F` taking type `A` which is a tuple of two lists of unary numbers (using unary not for the numbers themselves but for the individual digits, as allowed by OP) padded with leading zeroes (`[]`s) to the length of the output.

For example: `F<[[[1],[1],[1,1,1,1,1,1],[1,1,1,1,1,1,1,1]],[[],[1],[1],[1,1]]]>` (1168 + 0112) `= [[1],[1,1],[1,1,1,1,1,1,1,1],[]]` (1280)

## Explanation

```
//@ts-ignore                    Ignore any compilation errors in
type F<                      // Recursive main type F
  A,                         //   A is tuple of two lists of unary digits
  C=[]                       //   C is the digit to carry, default 0
>=
  // Match A to get the last and other digits of each number
  // X and Y are the current digits of each, G and H are the rest
  A extends[[...infer G,infer X],[...infer H,infer Y]]
    ?[...X,...Y,...C]extends // If it matched: Merge X,Y,C and match against
      [/* ... */,...infer R] //   ten 1s, storing what's left in R
        ?[...F<[G,H],[1]>,   //     If it matched, recurse with [G,H], C=[1]
          R]                 //       And append R
        :[...F<[G,H],[]>,    //     Otherwise, recurse with [G,H], C=[]
          [...X,...Y,...C]]  //       And append X,Y,C merged
    :[]                      // If the match failed, return the empty tuple

```

# Answer
> 5 votes
# Lua, ~~121~~ 119 bytes

```
load"A,B=...m=math.floor o=''c=0 for i=1,#A do L=#A-i+1O=A:sub(L,L)+c+B:sub(L,L)c=O/10 o=m(O%10)..o end return m(c)..o"

```

Try it online!

## Ungolfed

```
function add(A,B)
    floor=math.floor
    output=""
    carry=0
    for i=1,#A do
        L=#A-i+1
        sumResult=A:sub(L,L)+carry+B:sub(L,L)
        carry=sumResult/10
        output=floor(sumResult%10)..output
    end
    return floor(carry)..output
end

```

Inputs must be 0 padded to equal length.

# Answer
> 5 votes
# C (gcc), 62 bytes

```
f(a,b)char*a,*b;{*a=*a?48+(*b+=f(a+1,b+1)+*a-96)%10:0;b=*b>9;}

```

Try it online!

Input two `char*` strings. They must be padded with leading `0`s so they have same length and enough to contain the output. Modify the first array in-place for output.

# Answer
> 4 votes
# Vyxal, 35 bitsv2, 4.375 bytes

```
02(?(›

```

Try it Online!

Doesn't use `+`, but does use addition of some sort (incrementing the top of the stack). Takes inputs as two numbers.

## Vyxal, 47 bitsv2, 5.875 bytes

```
2(?(1}!

```

Try it Online!

No addition used, but still requires bignums to be inputted.

## Vyxal, 133 bitsv2, 16.625 bytes

```
ZEṠṘ0$(n+₀ḋ÷⅛)¾ṘJṅ⌊

```

Try it Online!

A version that takes both numbers as strings, and never has any values that could be a bignum on the stack (except at the end to remove a leading 0 from a string and to implicitly print - this could be done with string methods but it's shorter to use number conversion).

## Explained

```
02(?(›
0       # Push a 0 to the stack to act as a register
 2(     # Twice:
   ?(   #   For each number in the range(1, input() + 1):
     ›  #     Increment that 0
# The "register" value is then implicitly printed

```

Created with the help of Luminespire.

```
2(?(1}!
2(       # Twice:
  ?(     #   Number of input times:
    1    #     push a 1 to the stack
     }!  # Close all loops and push the length of the stack

```

Created with the help of Luminespire.

```
ZEṠṘ0$(n+₀ḋ÷⅛)¾ṘJṅ⌊
ZEṠ                  # Zip the input strings together, evaluate the digits in each pair, and vectorise sums
   Ṙ0$               # Reverse it, and push a 0 underneath it. This will act as the carry.
      (      )       # For each digit in that list,
       n+            #   Add the carry to that digit, consuming the carry
         ₀ḋ          #   Divmod by 10
           ÷⅛        #   And add the mod value to the global array, leaving the div value on the stack as the new carry.
              ¾ṘJ    # Push the global array, reverse it, and prepend the carry
                 ṅ⌊  # Convert to a single string and cast to int, removing any leading 0s.

```

Created with the help of Luminespire.

# Answer
> 4 votes
# Factor, ~~39 31~~ 43 bytes

```
[ 0 -rot [ + + 10 /mod ] 2map swap suffix ]

```

Try it online!

Non-builtin counterpart to the `+` answer. Takes two reversed, padded lists of digits as input and outputs the reversed answer as a list of digits.

# Answer
> 4 votes
# ISO C23 (clang 16), 42 bytes

`_BitInt(constant)` is a new C23 feature for fixed-width integers, wide or small. Implementations can have limits (`BITINT_MAXWIDTH`) on how wide they support, but clang 16 is wide enough for the problem's stated range of \[0, 10256). log2(10^256) rounds up to 851 bits required. 960 is the largest 3-digit number that's a multiple of 64 (not required, I just chose for efficiency); you can use `unsigned _BitInt(999)` if you want.

```
typedef _BitInt(960)T;T f(T*a,T b){*a+=b;}

```

**Updates the caller's `a` by reference.** Using the return value would be undefined behaviour (and in practice isn't useful even in a debug build.)

Works in practice with clang 16 (**Godbolt** shows it compiles to a sequence of `add`/`adc` instructions for x86-64, with some wasted loads/stores). But not GCC 13.2 or 14-trunk: *error: '\_BitInt' argument '960' is larger than 'BITINT\_MAXWIDTH' '575'*. (The Godbolt link also includes a simple test caller in `main`, but AFAIK there isn't convenient support for `printf` of big `_BitInt` values, and I didn't bother writing a hexdump.)

C23 doesn't allow implicit-`int` return values, and `T` is a shorter type-name than explicit `void` or `int`. But in C (unlike C++) it's *not* UB for execution to fall off the end of a non-`void` function, so we can declare it with a short type-name as the return type and still not actually `return`  anything, if implicit-`int` isn't an option. `void f(...)` would cost 3 extra bytes. Or actually returning by value like `T f(T a,T b){return a+b;}` costs an extra 5.

`typedef _BitInt(960)T;` is one byte shorter than `#define T _BitInt(960)`+newline. The more readable version is 43 bytes:

```
#define T _BitInt(960)
T f(T*a,T b){*a+=b;}

```

Related: https://stackoverflow.com/questions/61411865/how-do-you-use-clangs-new-custom-size-int-feature

---

**Clang provides `_BitInt` as an extension in older C modes, and in C++ mode.**

# C89 (clang 16), 40 bytes

```
typedef _BitInt(960)T;f(T*a,T b){*a+=b;}

```

Attempt This Online!

With default options (I think `-std=gnu11`), clang 16 requires `-Wno-implicit-int`, otherwise we get an error: *source.c:2:1: error: type specifier missing, defaults to 'int'; ISO C99 and later do not support implicit int \[-Wimplicit-int\]*. (And yes, in clang it's an error, not a warning, even without `-Werror`.)

But `-std=gnu89` or `c89` is allowed "for free" without having to count those compiler command-line options as part of the size of the answer. (I think? I can't find the relevant meta Q&A.) This feels like bending the rules because I'm using a very recent clang extension, but is arguably not breaking them. It compiles to the same asm on Godbolt.

# C++ (clang 16), 43 bytes

```
using T=_BitInt(960);void g(T&a,T&b){a+=b;}

```

C++ `using` is shorter than C `typedef` or `#define`, but falling off the end of a non-void function is UB in C++, not just if the caller uses the result. (`void` didn't exist in the early days of C, but existed from the start for C++.)

With `T` as the return type but no `return` statement, clang `-Os` emits zero instructions (not even `ret`) for the function. With optimization disabled, clang emits a `ud2` (illegal instruction) at the end instead of `ret`. (Godbolt)

`using T=_BitInt(960);T g(T&a,T&b){return a+b;}` is 46 bytes.

Taking both args by reference is probably better for efficiency in the caller. In the callee, clang still saves enough call-preserved registers to load a whole arg into registers, instead of working on a couple chunks at a time. And that's just addition; things get really hairy with division or multiplication. (But unlike Clang 14, division is supported for big `_BitInt` types, both by small constants and by other variables. Clang 15 dropped the max bit width to 128; Clang 16 widened it again.)

# Answer
> 3 votes
# Retina 0.8.2, ~~49~~ 44 bytes

```
O#$`.
$.%`
¶

M!`..
.
$*
+`¶1{10}
1¶
%M`1
¶

```

Try it online! Takes input on separate lines but link is to test suite that splits on  `.`  for convenience. Requires both inputs to be 0-padded to the same length. Explanation:

```
O#$`.
$.%`
¶

M!`..

```

Transpose the inputs.

```
.
$*

```

Convert to unary, summing each pair of digits.

```
+`¶1{10}
1¶

```

Perform any necessary carries.

```
%M`1

```

Convert to decimal.

Join all of the digits together.

Retina 1.0 has some support for bignums which does include addition so here's how it would be done:

```
L$`¶
$.($`*_$'*

```

Try it online! Takes input on separate lines but link is to test suite that splits on  `.`  for convenience. Explanation:  matches the newline between the numbers, but the numbers themselves can be retrieved via `$`` and `$'`. The `*` operator notionally converts them to unary and the `$.(` then converts the sum to decimal, although the underlying code simply sums the two bignums directly.

# Answer
> 3 votes
# C (clang), ~~73~~ ~~69~~ 58 bytes

```
c;f(*a,*b,n){for(;n--;c/=10)a[n]=(c+=a[n]+b[n]-96)%10+48;}

```

Try it online!

*Saved 4 bytes thanks to tsh*
*Saved 11 bytes thanks to Peter Cordes*

Inputs two wide-charater strings, padded to the length of the expected output.
Returns the sum in the first input string.

# Answer
> 3 votes
# Ruby, ~~78 67 59~~ 49 bytes

```
->a,b{c=0;a.zip(b).map{s=_1+_2+c;c=s>9?1:0;s%10}}

```

Attempt This Online!

My first Ruby submission! This is probably a little golfable but I'm pretty happy with it considering I have almost zero Ruby experience. Suggestions are welcome!

Implements long addition on two lists of digits in reverse order padded to the length of the output with zeroes, and outputs a list of digits in reverse order. Explanation:

* `->a,b{...}` Proc (anonymous function) taking parameters `a` and `b`

+ `c=0;` Set the `c` (the carried digit) to 0
    + `a.zip(b)` Zip `a` with `b` to get a list of pairs of digits
    + `.map{...}` Map each pair of digits to

    - `s=_1+_2+c;` Set `s` to the sum of the two digits and the carry
        - `c=s>9?1:0;` Set `c` to 1 if `s` is greater than 9, or 0 otherwise
        - `s%10` Return the ones place of `s` by taking it modulo 10

# Answer
> 3 votes
# JavaScript (Node.js), 63 bytes

```
f=(a,b,c=0)=>(c-=~a.pop()+~b.pop()+2)||a+b?f(a,b,c/10|0)+c%10:a

```

Try it online!

no bigint

# Answer
> 2 votes
# Charcoal, 21 bytes

```
ＰＳ¶Ｓ¶Ｗⅈ«←Ｐ←⮌ＩΣＥＫＤ³↑Σκ

```

Try it online! Link is to verbose version of code. Takes input as two strings of equal length but spaces can be used for padding and outputs the input strings and their sum. Explanation:

```
ＰＳ

```

Write the first string to the canvas without moving the cursor.

Move down a line.

Write the second string to the canvas.

Move down another line.

```
Ｗⅈ«

```

Repeat until the cursor reaches the left column.

Move left.

```
Ｐ←⮌ＩΣＥＫＤ³↑Σκ

```

Overwrite the current character with the sum of the column, overflowing any carry to the left.

# Answer
> 2 votes
# Perl 5, 84 bytes

```
sub f{($x,$y,$c,$s)=@_;$x|$y?f((map{s/.?$/$c+=$&;''/er}$x,$y),$c>9,$c%10 .$s):$c.$s}

```

Try it online!

# Answer
> 2 votes
# x86-64 machine code, ~~10~~ 8 bytes

A function that adds two little-endian binary Bigintegers of the same (non-zero) length, updating the destination in-place, using add-with-carry as a building block as it was designed for this.

It takes 2 pointer args and a count of how many 32-bit chunks, like `add_bignum(uint32_t *rdi_dst, uint32_t *rsi_src, size_t count_rcx)`. (That matches the x86-64 SysV calling convention if you use a dummy 3rd arg to fill the EDX slot.) The same machine code works in 32-bit mode, since `lodsd` and `stosd` work with whatever the native pointer size is.

It returns CF = carry-out from the top element. (If you want that to be part of the output, zero-extend the inputs with an extra 0 element at the top, and include that in the count.)

```
; NASM listing: machine code | source
               add_bignum:
 F8               clc                ; CF=0, no carry-in to the bottom.
                                     ; Peeling a first iteration using ADD would cost more bytes
               .loop:                ;do {
 AD               lodsd                ; eax = [rsi]; rsi+=4 without affecting FLAGS
 13 07            adc   eax, [rdi]
 AB               stosd                ; [rdi] = eax; rdi+=4 without affecting FLAGS
 E2 FA            loop  .loop        ; }while(--rcx);
 C3               ret

```

---

Add-with-carry (`adc`) chains the carry-out from the top of one chunk into the carry-in for the next chunk. As the loop iterates, it's like one wide ripple-carry adder over the full width of the arrays. (With carry-lookahead or whatever optimizations exist inside the CPU's ALUs happening within each chunk to run it with single-cycle latency. But as far as the result is concerned, it's like one long chain of full-adders, with the same hardware reused by software feeding the carry-out of the last instruction to the carry-in of the next. Carry only propagates from low to high in both addition and subtraction. It doesn't matter what element-size you use for it, as long as you get all the bytes of your bigints and chain the carry correctly.)

Bigint performance notes: the `loop` instruction is slow except on recent AMD CPUs, where it's actually really handy for loops that want to preserve FLAGS. It's too bad Intel didn't make it fast. Normal bigint loops on Sandybridge and later use `dec ecx / jnz` which leaves only CF unmodified, because Sandybridge has cheap partial-flag merging instead of stalling. And Broadwell and later don't merge at all; uops that want both parts of FLAGS just read it as 2 separate inputs, which is why `cmovbe` and `cmova` are still 2 uops while others are down to 1 uop. So the bigint looping problem has been solved that way, unlike on older P6-family CPUs where partial-flag stalls are a real problem.

Also, for performance, memory *source* `adc` is better on Intel CPUs, with a separate `mov` store. (Fun fact: memory destination `adc` has an extra uop beyond what you'd expect because of arcane microarchitectural reasons involving lack of TLB coherency across the uops of one instruction, according to Andy Glew.)

Also obviously using 64-bit operand-size would go twice as fast as 32-bit, or 8x as fast as bytes, for the same number of bytes. (Instruction fetch/decode isn't the bottleneck on modern CPUs with a uop cache, so the code-size differences aren't very significant for a hot loop). That costs an extra REX prefix on most instructions so I didn't use it in the initial version with 32-bit elements.

**TL:DR: un-golfing this code to something that performs well is more than just the obvious changes.** (Especially before the last update.) Look at the hand-written asm in GMP for production-quality example. (e.g. https://github.com/sethtroisi/libgmp/blob/master/mpn/x86\_64/coreisbr/aors\_n.asm is the add-or-sub template for `adc` or `sbb` loops for Sandybridge-family. It uses some `jrcxz` instead of just `dec/jnz` at the bottoms of loops, but I think the main unrolled loop uses `dec/jnz`.)

---

A previous version of this answer used memory-destination `adc [edi], al`, having to use byte operand-size instead of dword so we could use 1-byte `inc` in 32-bit mode. Thanks @m90 for reminding me of the standard lods / stuff / stos pattern which has the added bonus of allowing memory-source `adc`! My comments below are about why that 1-byte version was so inefficient:

Normally you can use `scasd` to increment RDI by 4, as long as it's a valid pointer, but that does a compare as well as load which overwrite FLAGS, breaking the chain of carry propagation through CF. Some shenanigans like pointing ESP at this array and using 1-byte `pop eax` then `adc [esi], eax` and a dummy `lodsd` to increment ESI might work, but would probably cost more bytes than `lea edi, [edi+4]` (and a signal handler could clobber the array). Maybe we could expect our caller to pass one of the bigints by value on the stack. And we'd still have to push the return address back again.

So ~~definitely the smallest~~ (and lowest performing) is to use 1-byte "limbs", making the pointer increment a single-byte (in 32-bit mode) `inc`, which sets the other FLAGS (all of SPAZO), but not CF. Other code can process the same bigint in larger chunks; **the limb size is only relevant to the count the caller passes, not anything else about the layout.**

# Answer
> 2 votes
# , 30 bytes

```
\(x,y)c(0,z<-x+y)%%10+c(z>9,0)

```

Attempt This Online!

Input as vectors of decimal digits, padded to the same length with leading zeros (or 27 bytes if the padding always contains at least one leading zero).
Automatic vectorization of (most) functions in R makes this pretty easy.

---

# , 41 bytes

```
\(x,y)c(0,z<-c(y&0,x)+c(x&0,y))%%10+(z>9)

```

Attempt This Online!

Input as vectors of decimal digits, no padding required. Output can contain (possibly many) leading zeros.

---

# , ~~90~~ 58 bytes

```
\(x,y,a=c(0,z<-c(y&0,x)+c(x&0,y))%%10+(z>9))a[cumsum(a)>0]

```

Attempt This Online!

Input as vectors of decimal digits, no padding required. Output has no leading zeros.

# Answer
> 2 votes
# C, 54 bytes

Binary bigint using 8 bits per `int`, in little-endian limb order. Carry-out still fits within an `int` where we can get it with a shift. `void f(int *dst, int *src, int n)`. Updates the destination in place

```
x;f(*a,*b,n){for(x=0;n--;*a++&=255)x=*a+=x/256+*b++;}

```

Try it online!

Iterates over the arrays, `a[i] += b[i] + carry_in`, truncating dst elements to 8 bits. `x` = un-truncated addition result, so the carry-out is in its 9th bit. It's non-negative since `int` is at least 16-bit, so we can do `x/256` = `x>>8` to get it as a 0 / 1 integer that has the right place-value for the next limb.

9 bits per limb would still cost the same code size (`&=511` and `x/512`), but more bits would need longer constants. I picked 8 because it's a round number, and easy to pack down to bytes to avoid the wasted space. (Making it a plausible format for larger code-golfed programs that want to use this.)

On a 64-bit machine with 32-bit `int`, this supports numbers up to `8*(2^31-1)` bits wide. That's vastly larger than the required 10^256 which only requires 851 bits. I could have used just 4, 2 or even 1 bit per limb to make the constants even smaller. Or 3 bits per limb (`&=7` and `x/8`); it doesn't have to be a power-of-2 number of bits. Using up 4x the amount of space seemed more reasonable than wasting 31x the amount, and more plausible for code converting to this format.

---

Real-life code uses this technique, but with 30 bits per `uint32_t` for example in CPython, since they avoid using hand-written asm for more efficient bigint on machines that have a carry flag. (See my codereview answer discussing BigInt implementation techniques, that using base 10 is highly inefficient, although base 10^9 in 32-bit chunks is good for efficient conversion to/from decimal strings, as in Extreme Fibonacci code golf.) Multiply uses stuff like `a * (uint64_t)b` as a widening multiply.

Partial-word bigint formats (not using all the bits per chunk) also allow deferring carry for SIMD implementations (as Mysticial explains), but that requires writing code that's aware of it.

C sucks at exposing add-with-carry or sub-with-borrow, especially carry-*in* to the same element where you want a carry-out. No portable functions for this, so it's up to compilers to recognize some idioms, such as `carry = (a+b)<a` for unsigned types. Or there are non-portable intrinsics such as for x86, but those often compile to poor asm for more than 2 limbs, or in a loop. But things have improved some recently, with a combination of some compilers getting better at keeping carry-out in the carry flag (instead of materializing a 0/1 integer in a register), and a way of writing portable ISO C source that actually gets clang to compile to a chain of `adc` instructions on ISAs that have a carry flag.

This version is of course optimizing for source size, not performance or storage density.

# Answer
> 1 votes
# dc, ~~4~~ 3 bytes

```
?+p

```

Try it online!

# Answer
> 0 votes
# AWK, 12

```
{print$1+$2}

```

Try it online!

---
Tags: code-golf, math, number
---


title: XOR multiplication

text:
# Question
Title: XOR multiplication
You goal is to implement the operation of XOR (carryless) multiplication, defined below, in as few bytes as possible.

If we think of bitwise XOR (`^`) as binary addition without carrying

```
   101   5
^ 1001   9
  ----
  1100  12

  5^9=12

```

we can perform XOR multiplication `@` by doing binary long-multiplication but doing the adding step without carrying as bitwise XOR `^`.

```
     1110  14
   @ 1101  13
    -----
     1110
       0
   1110
^ 1110
  ------
  1000110  70

  14@13=70

```

(For mathematicians, this is multiplication in the polynomial ring \\$F\_2\[x\]\\$, identifying polynomials with natural numbers by evaluating at \\$x=2\\$ as a polynomial over \\$\mathbb Z\\$.)

XOR multiplication commutes `a@b=b@a`, associates `(a@b)@c=a@(b@c)`, and distributes over bitwise XOR `a@(b^c)=(a@b)^(a@c)`. In fact, it is the unique such operation that matches multiplication `a@b=a*b` whenever `a` and `b` are powers of `2` like `1,2,4,8...`.

**Requirements**

Take two non-negative integers as input and output or print their XOR-product. This should be as numbers or their decimal string representations, not their binary expansions. Fewest bytes wins.

Don't worry about integer overflows.

Here are some test cases formatted as `a b a@b`.

```
0 1 0
1 2 2
9 0 0
6 1 6
3 3 5
2 5 10
7 9 63
13 11 127
5 17 85
14 13 70
19 1 19
63 63 1365

```

# Answer
> 36 votes
# x86 machine code: 7 bytes

```
66 0F 3A 44 C1 00 C3  pclmulqdq xmm0, xmm1, 0 \ ret

```

Only two instructions. `pclmulqdq` does the heavy lifting, it literally implements that type of xor-multiplication. `ret` to make it a callable function, hopefully satisfying the requirement of "outputting" the result (in the return value, `xmm0`). Putting integer arguments in `xmm` args is a bit unusual, but I hope you'll forgive me.

# Answer
> 15 votes
# Z80, 11 bytes

```
B7 CB 32 30 01 B3 C8 CB 23 18 F6

```

The code is called as a function. `a` and `b` are in `D` and `E` (the order doesn't matter) and the answer is stored in `A` when the code returns (there are no I/O functions).

```
B7      XOR A     //  A^=A (A=0)
CB 32   SRL D     //    CARRY = lsb(D), D>>=1, ZERO = D==0
30 01   JR NC, 1  //    jump 1 byte if not CARRY
B3      XOR E     //      A^=E, ZERO = A==0
C8      RET Z     //    return if ZERO
CB 23   SLA E     //    E<<=1
18 F6   JR -10    //    jump -10 bytes

```

It produces the correct results for all test input except `63@63` which returns `85` because all the registers are 8-bit and 1365 mod 256 = 85 (integer overflow).

# Answer
> 9 votes
# Pyth, ~~13~~ 12 bytes

```
uxyG*HQjvz2Z

```

Demonstration.

```
uxyG*HQjvz2Z
                  Implicit:
                  z = input()
                  Q = eval(input())
                  Z = 0

       jvz2       The first input, written in base 2, like so: [1, 0, 1, ...
u      jvz2Z      Reduce over the binary representation, starting with 0.
 x                XOR of
  yG              Twice the previous number
    *HQ           and the second input times the current bit.

```

---

Old version, 13 bytes:

```
xFm*vz.&Q^2dQ

```

Demonstration.

# Answer
> 9 votes
# C, ~~44~~ 38 bytes

*Thanks to nimi, we now use recursion for 6 fewer bytes!*

```
f(a,b){return b?(b&1)*a^f(a*2,b/2):0;}

```

We define a function `f` which takes `a`, `b`.

This can be called like:

```
printf("%d @ %d = %d\n", 13, 14, f(13, 14));

```

Which outputs:

`13 @ 14 = 70`

Try the test cases online!

# Answer
> 8 votes
# J, 14 bytes

```
*/(~://.@)&.#:

```

Usage:

```
   5 (*/(~://.@)&.#:) 17     NB. enclosing brackets are optional
85

```

Explanation (reading mostly from right to left; `u` and `v` stand for arbitrary functions):

* `u&.#:` applies `u` to the vectors of the binary representations of the input numbers then turn the result back to an integer (`u&.v == v_inverse(u(v(input_1), v(input_2)))`)
* `*/` products (`*`) of inputs in the Descartes product (`/`) of the two binary vector
* `v(u@)` apply `u` to `v` (to the Descartes product)
* `u/.` apply `u` to every anti-diagonal of the Descartes product (anti-diagonals represent the 1st, 2nd, ... digits in the binary representation)
* `~:/` reduce (`/`) an anti-diagonal with XOR operation (`~:`)
* The last step is generating an integer from the binary vector which the first point takes care of.

Try it online here.

# Answer
> 8 votes
# CJam, ~~14~~ 13 bytes

```
q~2bf*{\2*^}*

```

**How it works**:

We first get the long multiplication results and then work our way up starting from the bottom two pairs.

```
q~                e# Eval the input. This puts the two numbers on stack
  2b              e# Convert the second number to binary
    f*            e# Multiply each bit of second number with the first number
                  e# This leaves an array with the candidates to be added in the long
                  e# multiplication step
      {    }*     e# Reduce on these candidates. Starting from the bottom
       \2*        e# Bit shift the lower candidate
          ^       e# XOR each other and continue

```

Try it online here

# Answer
> 8 votes
# Python 2, 35 bytes

```
f=lambda m,n:n and n%2*m^f(2*m,n/2)

```

Call like `f(13, 14)`. I think most languages with a similar construct will converge on something like this.

# Answer
> 6 votes
# Java, 62

```
(x,y)->{int r=0,i=0;for(;i<32;)r^=x*((y>>i)%2)<<i++;return r;}

```

## Expanded

```
class XORMultiplication {
    public static void main(String[] args) {
        IntBinaryOperator f = (x, y) -> {
                    int r = 0, i = 0;
                    for (; i < 32;) {
                        r ^= x * ((y >> i) % 2) << i++;
                    }
                    return r;
                };
        System.out.println(f.applyAsInt(14, 13));
    }
}

```

# Answer
> 4 votes
## Perl - 35 Bytes

```
#!perl -p
$\^=$`>>$_&1&&$'<<$_ for-/ /..31}{

```

Counting the command line option as one. Input is taken from `STDIN`, space separated.

**Sample usage:**

```
$ echo 13 11 | perl xormul.pl
127
$ echo 5 17 | perl xormul.pl
85
$ echo 14 13 | perl xormul.pl
70
$ echo 19 1 | perl xormul.pl
19
$ echo 63 63 | perl xormul.pl
1365

```

# Answer
> 4 votes
# Jelly, 12 bytes

```
BJ’2*U×B{×^/

```

Try it online!

## How it works

```
BJ’2*U×B{×^/ - Main link. Takes a on the left, b on the right
B            - Binary representation of a
 J           - Replace each element with its index
  ’          - Decrement
   2*        - Raise each to the power 2
     U       - Reverse
       B{    - Yield the binary representation of a
      ×      - Multiply the bits by the powers
         ×   - Multiply b by the results
          ^/ - Reduce by XOR

```

# Answer
> 4 votes
# Jelly, ~~7~~ 6 bytes

```
Bæc/ḂḄ

```

Try it online!

*-1 thanks to Jonathan Allan*

Takes a list of `[a, b]`. (The dyadic equivalent is the very fun-looking `BæcḂḄɓB`.)

```
B         Convert a and b to their binary digits,
 æc/      and convolve them.
    Ḃ     Take each mod 2
     Ḅ    and convert from binary.

```

# Answer
> 3 votes
# Haskell, 50 bytes

```
import Data.Bits
_#0=0
a#b=b.&.1*a`xor`2*a#div b 2

```

A translation of @BrainSteel's C answer. Usage example:

```
map (uncurry (#)) [(0,1),(1,2),(9,0),(6,1),(3,3),(2,5),(7,9),(13,11),(5,17),(14,13),(19,1),(63,63)]
[0,2,0,6,5,10,63,127,85,70,19,1365]

```

# Answer
> 3 votes
# Julia, ~~35~~ ~~33~~ 30 bytes

```
f(a,b)=b%2*a$(b>0&&f(2a,b÷2))

```

This creates a recursive function `f` which takes two integers and returns the XOR product of the inputs.

Ungolfed:

```
function f(a, b)
    # Bitwise XOR : $
    # Short-circuit AND : &&

    b % 2 * a $ (b > 0 && f(2a, b ÷ 2))
end

```

Saved a couple bytes with encouragement from Sp3000!

# Answer
> 3 votes
# MMIX, 28 bytes (7 instrs)

(jelly xxd)

```
00000000: e3020000 7aff0001 c60202ff 3f000001  ẉ£¡¡z”¡¢İ££”?¡¡¢
00000010: 37010101 5b00fffc f8030000           7¢¢¢[¡”‘ẏ¤¡¡

```

Disassembly:

```
clmul   SETL $2,0       // r = 0
0H      ZSOD $255,$0,$1 // loop: t = a odd? b : 0
        XOR  $2,$2,$255 // r ^= t
        SRU  $0,$0,1    // a >>= 1
        SLU  $1,$1,1    // b <<= 1
        PBNZ $0,0B      // iflikely(a) goto loop
        POP  3,0        // return r

```

You could get a 128-bit answer out of this with about three more instructions, I think.

# Answer
> 2 votes
# Python 2, ~~104~~ ~~91~~ ~~78~~ 66 bytes

```
def y(a,b,c=0):
 for _ in bin(b)[:1:-1]:c^=int(_)*a;a<<=1
 print c

```

Take the bits of `b` in reverse order, ending before you hit the `'0b'` at the start of the string. Multiply each one by `a` and `xor` with the total, then left-shift `a`. Then print the total.

# Answer
> 2 votes
# Mathematica, 40 bytes

```
BitXor@@(#2BitAnd[#,2^Range[0,Log2@#]])&

```

# Answer
> 2 votes
# Go, 63 bytes

```
func f(a,b uint)uint{if a<1{return 0};return a%2*b^f(a/2,b*2)}

```

Complete example:

http://play.golang.org/p/-ngNOnJGyM

# Answer
> 2 votes
# GAP, 368 Bytes

> For mathematicians, this is multiplication in the polynomial ring F\_2\[x\], identifying polynomials with natural numbers by evaluating at x=2 as a polynomial over Z.

Sure, let's do that! (this is only loosly golfed, the point was more to move into F2\[x\] and do the calculations more than any attempt at being a winning entry)

Here's the code

```
f:=function(i,j)R:=PolynomialRing(GF(2));x:=IndeterminatesOfPolynomialRing(R);x:=x[1];a:=function(i)local n,r;r:=0*x;while not i=0 do n:=0;while 2^n<=i do n:=n+1;od;n:=n-1;r:=r+x^n;i:=i-2^n;od;return r;end;b:=function(r)local c,i,n;i:=0;n:=0;for c in CoefficientsOfUnivariatePolynomial(r) do if c=Z(2)^0 then n:=n+2^i;fi;i:=i+1;od;return n;end;return b(a(i)*a(j));end;

```

Here's the ungolfed code with explanation:

```
xor_multiplication:=function(i,j)
    R:=PolynomialRing(GF(2));
    x:=IndeterminatesOfPolynomialRing(R);
    x:=x[1];
    to_ring:=function(i)
        local n,r;
        r:=0*x;
        while not i=0 do
            n:=0;
            while 2^n<=i do
                n:=n+1;
            od;
            n:=n-1;
            r:=r+x^n;
            i:=i-2^n;
        od;
        return r;
    end;
    to_ints:=function(r)
        local c,i,n;
        i:=0;n:=0;
        for c in CoefficientsOfUnivariatePolynomial(r) do
            if c=Z(2)^0 then
                n:=n+2^i;
            fi;
            i:=i+1;
        od;
        return n;
    end;
    return to_ints( to_ring(i)*to_ring(j));
end;

```

Okay, so first off, we create the univariate polynomial ring over the field F2 and call it `R`. Note that `GF(2)` is F2 in GAP.

```
R:=PolynomialRing(GF(2));

```

Next, we are going to assign the GAP variable `x` to the indeterminate of the ring `R`. Now, whenever I say `x` in GAP, the system will know I am talking about the indeterminate of the ring `R`.

```
x:=IndeterminatesOfPolynomialRing(R);
x:=x[1];

```

Next, we have two functions, which are inverse maps of each other. These maps are both onto, but they are not structure preserving, so I couldn't figure out a better way to implement them in GAP. There almost certainly is a better way, if you know it, please comment!

The first map, `to_ring` takes an integer and maps it to its corresponding ring element. It does this by using a conversion to binary algorithm, where every `1` that would appear in binary is replaced by an `x^n` where `n` is the appropriate power that 2 would take if the number was indeed binary.

```
    to_ring:=function(i)
        local n,r;
        r:=0*x;                 # initiate r to the zero element of R
        while not i=0 do        # this is a modified binary algorithm
            n:=0;
            while 2^n<=i do
                n:=n+1;
            od;
            n:=n-1;
            r:=r+x^n;
            i:=i-2^n;
        od;
        return r;
    end;

```

The next function reverses this. `to_ints` takes a ring element and maps it to its corresponding integer. I do this by getting a list of the coefficients of the polynomial and for each nonzero coefficient, the result is increased by 2^n, in the same way that we would convert binary to decimal.

```
    to_ints:=function(r)
        local c,i,n;
        i:=0;n:=0;
        for c in CoefficientsOfUnivariatePolynomial(r) do
            if c=Z(2)^0 then

                 # ^-- Right here you'll notice that the Z(2) is basically '1' in GF(2). So Z(2)^0 ~ 1 and Z(2)*0 ~ 0
                 # effectively, this line checks for nonzero coefficients

                n:=n+2^i;
            fi;
            i:=i+1;
        od;
        return n;
    end;

```

For the final step, we call these functions. We take the two integer inputs, convert them into elements in the ring `R`, then multiply these elements together, and send the product back to the integers.

```
return to_ints( to_ring(i)*to_ring(j));

```

# Answer
> 2 votes
# Jelly, 16 bytes

```
Ḥ⁴BL’¤Ð¡U×"⁴B¤^/

```

Try it online!

# Answer
> 2 votes
# ARM Thumb-2 (NEON), 6 bytes

Eat my Thumb, `pclmullqlqdqdqdqdq`. ARM has boring builtins, too!

```
ef80 0e01 4770

```

Assembly code:

```
        .syntax unified
        .arch armv7-a
        .fpu neon
        .thumb
        .globl xormul_boring_neon
        .thumb_func
xormul_boring_neon:
        // q0[0-8] = d0[0-8] @ d1[0-8]
        vmull.p8 q0, d0, d1
        bx       lr

```

Input: two 8-bit values in `d0` and `d1` Output: the 16-bit product in `q0`

This actually multiplies 8 packed bytes together.

# ARM Thumb-2, manual, 14 bytes

Ok, to make up for it, here is a fully scalar version which does a 32x32 multiply with a 32-bit result.

```
2300 0849 bf28 4043 0040 d1fa 4770

```

Assembly code:

```
        .syntax unified
        .arch armv6t2
        .thumb
        .globl xormul_scalar
        .thumb_func
        // r3 <- r0 @ r1
xormul_scalar:
        // acc <- 0
        movs    r3, #0
.Lloop:
        // test each bit in y by using lsrs carry-out
        lsrs    r1, r1, #1
        // was the bit set?
        it      cs
        // if so, acc ^= x
        eorcs   r3, r0
        // shift x left
        lsls    r0, r0, #1
        // loop while x is non zero
        bne     .Lloop
.Lend:
        // return in r3
        bx      lr

```

Equivalent C code:

```
uint32_t xormul_scalar(uint32_t x, uint32_t y)
{
    uint32_t acc = 0;
    do {
        if (y & 1)
            acc ^= x;
        y >>= 1;
    } while ((x <<= 1));
    return acc;
}

```

The numbers to be multiplied are in `r0` and `r1`, and the result is in `r3`.

It is a fairly basic shift and xor loop.

Yet another case of `lsls` and `lsrs` being far too useful than they deserve to be.

Try it online! (sorta): demo in Travis

# Answer
> 2 votes
# 05AB1E, 8 bytes

```
Îbv·yI*^

```

Try it online or verify all test cases.

**Explanation:**

```
Î         # Push 0 and the first input
 b        # Convert it to a binary string
  v       # Loop over each bit `y` of this string:
   ·      #  Double the current integer
    y     #  Push bit `y`
     I*   #  Multiply it by the second input
       ^  #  Bitwise-XOR the two together
          # (after the loop, the result is output implicitly)

```

# Answer
> 2 votes
# Wolfram Language (Mathematica) v13.3+, 38 bytes

```
(F=2~FiniteField~+##;F@#2F@#)@"Index"&

```

Input `[a, b]`.

Version 13.3 introduced `FiniteField`, which is nicer to golf with than `FiniteFields`GF`. Getting an integer out of a `FiniteFieldElement` is still a little verbose, though.

# Answer
> 1 votes
## Dart, ~~34~~ 32 bytes

```
m(a,b)=>a<1?0:a%2*b^m(a~/2,b*2);

```

Straight-forward recursive implementation.

# Answer
> 1 votes
## Ruby, ~~76~~ ~~75~~ 73 bytes

```
a,b=$*.map{|x|x.to_i}
o=0
while(b>0)
o^=a&-(b&1)
a<<=1
b>>=1
end
puts(o)

```

# Ruby, 60 bytes (function only, no I/O)

```
def t(a,b)
o=0
while(b>0)
o^=a&-(b&1)
a<<=1
b>>=1
end
t
end

```

# Answer
> 1 votes
# gnuplot, 29 bytes

```
m(a,b)=a<1?0:a%2*b^m(a/2,b*2)

```

just like in Dart (see above)

# Answer
> 1 votes
# GNU Assembler(x86\_64 Mac OS X), 97 bytes

This is a proper function that can be called from C:

```
.text
.globl _f
_f:
movq %rdi,%xmm0;movq %rsi,%xmm1;pclmulqdq $0,%xmm1,%xmm0;movq %xmm0,%rax;ret

```

& can be tested with this C program:

```
#include <stdio.h>
int f(int a, int b);
#define p(a,b) printf("%d %d %d\n", a, b, f(a, b))
int main(void)
{
    p(0,1);
    p(1,2);
    p(9,0);
    p(6,1);
    p(3,3);
    p(2,5);
    p(7,9);
    p(13,11);
    p(5,17);
    p(14,13);
    p(19,1);
    p(63,63);
}

```

Note that on Mac OS X, you have to use `clang -x c` to compile it as C & not C++.

For linux(if I remember right), the code would be 95 bytes:

```
.text
.globl f
f:
movq %rdi,%xmm0;movq %rsi,%xmm1;pclmulqdq $0,%xmm1,%xmm0;movq %xmm0,%rax;ret

```

Strangely enough, this version is actually longer than defining the function in inline assembly, but that one was longer than the pure C solution we already have, so I decided to try assembly.

### edit

If it's counted by the assembled size(excluding any labels &c.), then it's

# x86\_64 Assembler, 22 bytes:

```
0:  66 48 0f 6e c7          movq         %rdi,  %xmm0
5:  66 48 0f 6e ce          movq         %rsi,  %xmm1
a:  66 0f 3a 44 c1 00       pclmullqlqdq $0,    %xmm1,%xmm0
10: 66 48 0f 7e c0          movq         %xmm0, %rax
15: c3                      ret

```

# Answer
> 1 votes
# , 53 bytes

```
f=function(x,y)`if`(y,bitwXor(x*y%%2,2*f(x,y%/%2)),0)

```

Try it online!

# Answer
> 1 votes
# JavaScript (Node.js), 29 bytes

```
f=(x,y)=>x&&f(x>>1,y)*2^x%2*y

```

Try it online!

Similar to https://codegolf.stackexchange.com/a/50246/

# Answer
> 1 votes
# Vyxal, 9 bytes

```
₌0b(dn⁰*꘍

```

Try it Online!

Ports the 05AB1E answer, so go upvote that too

## Explained

```
₌0b(dn⁰*꘍
₌0b       # Push 0 and the binary of the first input
   (      # to each bit:
    d     # double the top of the stack
     n⁰*  # multiply the bit by the second input
        ꘍ # and bit xor

```

# Answer
> 1 votes
# Pyt, 37 bytes

```
ɓąƖĐŁř⁻↔2⇹^**ĐŁ2%¬?ŕ:ŕÁ0á;ĐŁ`ŕʁ⊻ĐŁ⁻łŕ

```

Try it online!

Takes two integers a,b on separate lines

The following is worked on a=13, b=14

| Code | Stack | Description |
| --- | --- | --- |
| ɓąƖ | \[1,1,0,1\] | Pushes the **ą**rray corresponding to the **ɓ**its of 13 |
| ĐŁř⁻↔2⇹^\* | \[8,4,0,1\] | Converts array to corresponding powers of 2 |
| * | \[112,56,0,14\] | Multiplies the array by 14 |
| ĐŁ2%¬? | \[112,56,0,14\], True | does the array have an even length? |
| ŕ | \[112,56,0,14\] | If so, pop the boolean check |
| :ŕÁ0á | (skipped in this run) | Otherwise, append a 0 to the array |
| ;ĐŁ\`ŕʁ⊻ĐŁ⁻ł | \[70\], 0 | **ʁ**educe the array using XOR () while the **Ł**ength of the resulting array is greater than 1 |
| ŕ | \[70\] | **ŕ**emove the 0; implicit print |

# Answer
> 1 votes
# Itr, 9 bytes

`BàBC*µRxB`

online interpreter

## Explanation

```
            ; implicit input
BàB         ; convert input to bit lists
   C*µRx    ; polynomial multiplication in F2[X]
        B   ; convert bit-list to number
            ; implicit output

```

# Answer
> 1 votes
# Nekomata, 5 bytes

```
ᵃƂ×Öƃ

```

Attempt This Online!

```
ᵃƂ×Öƃ
ᵃƂ      Convert both inputs to binary digits
  ×     Convolve
   Ö    Modulo 2
    ƃ   Convert back to decimal

```

# Answer
> 0 votes
# golflua 68

```
x,y=I.r("*n","*n")r=0~@i=0,31r=B.x(r,x*B.ls(B.rs(y,i)%2,i+1))$w(r/2)

```

Does basically the same bitshifting as Ypnypn's Java answer, but seems to require the divide by 2 at the end to work correctly. Takes in values as stdin, examples below

```
> 14 13
70
> 19 1
19
> 5 17
85

```

# Answer
> 0 votes
## Ceylon, 90 bytes

```
alias I=>Integer;I x(I a,I b)=>[for(i in 0:64)if(b.get(i))a*2^i].fold(0)((y,z)=>y.xor(z));

```

This is just the algorithm as described: multiply `a` by `2^i` wherever the `i`th bit is set in `b`, and add them all together using xor. Iterates over `0:64` because Integers are 64-bit in Ceylon when running on JVM (lower when running as Javascript, but then `b.get(i)` just returns false).

Formatted:

```
alias I => Integer;

I x(I a, I b) =>
      [
        for (i in 0:64)
            if (b.get(i))
                a * 2^i
      ].fold(0)((y, z) => y.xor(z));

```

The alias safes here just a single byte.

# Answer
> 0 votes
# JavaScript (Node.js), 42 bytes

Port of the Java answer. Go upvote that!

```
x=>y=>(g=i=>i&&g(--i)^x*((y>>i)%2)<<i)(32)

```

Try it online!

---
Tags: code-golf, math, number, bitwise
---