# Question
Title: Appease Your Google Overlords: Draw the "G" Logo
Write a program or function that takes in a positive integer N, and outputs an N×N pixel image of Google's "G" logo according to this\* construction:

>

For example, if N is 400, a 400×400 pixel logo should be output, with correct dimensions and colors:

It should look accurate regardless of how large or small N is. e.g. here is N = 13:

Your code should not need to connect to the internet. For example, scaling an externally hosted svg is not allowed. (Scaling an svg encoded in your code would be fine though.)

Anti-aliasing may be used or not. It's up to you.

Notice that the horizontal bar of the "G" does not extend all the way to the right edge of the image. The circle curves normally inward on the right edge before it is cut off.

**The shortest code in bytes wins.**

---

<sup>** The construction of the logo has been simplified for this challenge. The correct construction can be seen here and here.*</sup>

# Answer
> 58 votes
# Mathematica, ~~229~~ ~~226~~ ~~225~~ ~~224~~ ~~221~~ ~~206~~ 169 bytes

Thanks @MartinEnder for 1 byte, @ChipHurst for **37 bytes!**

```
Graphics[{RGBColor@{"#EA4335","#FBBC05","#34A853","#4285F4"}[[#]],{0,-1}~Cuboid~{√24,1},Annulus[0{,},{3,5},{(2#-9)Pi/4,ArcCsc@5}]}&~Array~4,ImageSize->#,PlotRange->5]&

```

What a fun challenge!

# Explanation

```
...&~Array~4

```

Iterate from 1 to 4...

```
RGBColor@{"#EA4335","#FBBC05","#34A853","#4285F4"}[[#]]

```

Convert the color hex codes to `RGBColor` objects, so that they can be applied to the Google logo graphic. Change the color palette to the `<input>`th color.

```
{0,-1}~Cuboid~{√24,1}

```

Create a filled rectangle (2D cuboid), whose diagonal corners are (0, -1) and (sqrt(24), 1).

```
Annulus[0{,},{3,5},{(2#-9)Pi/4,ArcCsc@5}]}

```

Generate four filled quarter-`Annulus`s, centered at the origin, with inner radius 3 and outer radius 5. Do not draw past `ArcCsc@5` (where the blue segment ends).

```
Graphics[ ... , ImageSize->#,PlotRange->5]

```

Create a graphic with size N x N, from x = -5 to x = 5 (removes the padding).

# Outputs

N = 10

N = 100

N = 200

N = 10000 (click image for full resolution)

# Answer
> 45 votes
## C (Windows), 311 bytes

```
#include <windows.h>
main(int c,char**v){float x,y,a,b,N=atoi(*++v);HDC d=GetDC(GetDesktopWindow());for(x=0;x<N;x+=1)for(y=0;y<N;y+=1){a=2*x/N-1;b=2*y/N-1;SetPixel(d,x,y,(a>0&&a<.8&&b*b<.04)?0xF48542:(a*a+b*b>1||a*a+b*b<.36)?0xFFFFFF:(a*a<b*b)?((b<0)?3490794:5482548):(a<0)?376059:(b<-.2)?0xFFFFFF:0xF48542);}}

```

Takes "N" as command line argument and draws directly on the screen.

Un-golfed:

```
#include <windows.h>
// atoi() will work fine without any #include file!
// -> don't #include it!

main(int c,char **v)
{
    float x,y,a,b,N=atoi(*++v);

    /* Access the screen for directly drawing! */
    HDC d=GetDC(GetDesktopWindow());

    /* Iterate over the pixels */
    for(x=0;x<N;x+=1)
        for(y=0;y<N;y+=1)
    {
        /* Convert x,y into "relative" coordinates: The image
         * is 2.0x2.0 in size with (0.0,0.0) in the center */
        a=2*x/N-1;
        b=2*y/N-1;

        /* Draw each pixel */
        SetPixel(d,x,y,
            (a>0 && a<.8 && b*b<.04)?0xF48542: /* The bar of the "G" in the middle */
            (a*a+b*b>1 || a*a+b*b<.36)?0xFFFFFF: /* Not on one of the circle segments */
            (a*a<b*b)?((b<0)?0x3543EA:0x53A834): /* Top and bottom segments */
            (a<0)?0x5BCFB: /* Left segment */
            (b<-.2)?0xFFFFFF:0xF48542); /* Right segment: A bit more complicated... */
    }

    /* Note: Under good old Windows 3.x we would require to
     * call "ReleaseDC" here; otherwise the system would
     * "crash" (however the image would have been drawn!)
     * No need for this in modern Windows versions! */
}

```

# Answer
> 35 votes
# Python 2, ~~244~~ 220 bytes

using Martin Rosenau's transformation on the \[-1,1\]^2 plane and minor golfing like removing `0.` or brackets

```
N=input()
R=[2*z/(N-1.)-1for z in range(N)]
B="\xFF"*3,"B\x85\xF4"
print"P6 %d %d 255 "%(N,N)+"".join([B[0<x<.8and.04>y*y],["4\xA8S",B[y>-.2],"\xFB\xBC\x05","\xEAC5"][(x>y)+2*(-x>y)]][.36<x*x+y*y<1]for y in R for x in R)

```

Explanation:

```
N=input()
R=[2*z/(N-1.)-1for z in range(N)]
#N*N points on the [-1,1]^2 plane

B="\xFF"*3,"B\x85\xF4"
#white and blue

print"P6 %d %d 255 "%(N,N) + "".join(
#binary PPM header
 [
  B[0<x<.8and.04>y*y],
  #blue rectangle part of the G, or white
  ["4\xA8S",B[y>-.2],"\xFB\xBC\x05","\xEAC5"][(x>y)+2*(-x>y)]
  #[green, [white,blue], yellow, red]-arcs with 4 way selector
 ]
 [.36<x*x+y*y<1]
 #radius checker, outside=0 blue rectangle or white, inside=1 colored arcs
  for y in R for x in R
  #for all points
 )

```

Output as binary PPM, usage:

```
python golf_google.py > google.ppm

```

## Examples

* 13

* 50

* 100

* 1337

### previous 244 bytes solution

```
N=input()
S="P6 %d %d 255 "%(N,N)
R=range(N)
B=["\xFF"*3,"B\x85\xF4"]
for Y in R:
 for X in R:y=Y-N/2;x=X-N/2;S+=[B[0<x<0.4*N and abs(y)<0.1*N],["4\xA8S",B[y>-0.1*N],"\xFB\xBC\x05","\xEAC5"][(x>y)+2*(-x>y)]][0.3*N<(y**2+x**2)**.5<0.5*N]
print S

```

### Ungolfed beta Version before if/else elimination:

```
N=input()
print"P3 %d %d 255 "%(N,N)
R=range
M=N/2
r="255 0 0 "
g="0 255 0 "
b="0 0 255 "
c="255 255 0 "
w="255 255 255 "
for Y in R(N):
 for X in R(N):
  y=Y-M
  x=X-M
  d=(y**2+x**2)**.5 #radius
  if 0.3*N<d<0.5*N: #inside circle
   if x>y:          #diagonal cut bottom-left to top right
    if -x>y:        #other diagonal cut
     print r
    else:
     if y>-0.1*N:print b #leave some whitespace at blue
     else: print w
   else:
     if -x>y:
      print c
     else:
      print g
  else:
   if 0<x<0.4*N and -0.1*N<y<0.1*N: #the straight part of G
    print b
   else:
    print w

```

# Answer
> 27 votes
# JavaScript (ES6), ~~408 ... 321~~ 317 bytes

~~384 383 371 367 359 327 316 308~~ 304 bytes of JavaScript + ~~24~~ 13 bytes for the canvas element

```
(f=d.style).width=f.height=(d.width=d.height=n=prompt(f.background='#FFF'))+'px';q=n/2;with(d.getContext`2d`)['#EA4335','#FBBC05','#34A853','#4285F4'].map((c,i)=>beginPath(lineWidth=y=n/5,strokeStyle=fillStyle=c,arc(q,q,z=q-y/2,(j=2*i+1)*(r=-.7854),(j+(i-3?2:1.256))*r,1),stroke(),fillRect(q,z,q*.98,y)))
```

```
<canvas id=d>
```

1 byte saved by drawing counter-clockwise.
11 bytes saved on the HTML thanks to Conor O'Brien.
12 bytes saved using `with` block thanks to Prinzhorn.
4 bytes saved with better use of `z=q-y/2`.
8 bytes saved by using `parentNode` and `background` thanks to Alexis Tyler.
32 bytes saved by using a more precise drawing of the blue arc/bar so I don't need to erase a part of it anymore.
11 bytes saved by setting canvas css instead of its parentNode thanks to Tejas Kale.
8 bytes saved using `with` and `map` with a single statement, \`2d\` instead of `('2d')`, `n/5` instead of `.2*n` and initializing the background in the `prompt(...)`.
4 bytes saved replacing `Math.PI/4` by `.7854` which seems enough precision thanks to RobAu.

---

**Explanation:**

```
(f=d.style).width=f.height=(d.width=d.height=n=prompt(f.background='#FFF'))+'px';q=n/2

```

The canvas dimensions are initilized with user input and the background is set to white. `q` is initialized.

```
with(d.getContext`2d`)['#EA4335','#FBBC05','#34A853','#4285F4'].map((c,i)=>beginPath(lineWidth=y=n/5,strokeStyle=fillStyle=c,arc(q,q,z=q-y/2,(j=2*i+1)*(r=-.7854),(j+(i-3?2:1.256))*r,1),stroke(),fillRect(q,z,q*.98,y)))

```

For each color draws the circle part, with some adjustement for the last (blue) one. The bar is drawn for each color at the same place with the same dimensions so only the last (blue) one is visible.

# Answer
> 25 votes
# BBC BASIC, 177 bytes

Download interpreter at http://www.bbcbasic.co.uk/bbcwin/download.html

```
I.n
V.19;16,234,67,53,275;64272;1468;531;16,43060;83,787;16,34114;7668;n;n;
F.t=1TO8.256S.1/n
a=t*PI/4y=n*SIN(a)x=n*COS(a)V.18;t-1>>1,25,85,x*.6;y*.6;25,85,x;y;
N.PLOT101,0,-n/5

```

BBC BASIC uses 2 units=1 pixel, so we plot a G of radius `n` units (=n/2 pixels) at centre `n,n`.

The idea is to plot a series of radial lines, changing colour as appropriate. It was found that there were small gaps between the lines due to truncation of the numbers when converted to pixels, so thin triangles are actually plotted instead.

Once the sweep of lines is completed, the cursor is at the top right corner of the blue area. A single coordinate for the diagonally opposite corner is given to draw a rectangle in order to complete the shape.

**Ungolfed**

```
INPUTn
REM reprogram pallette
VDU19;16,&EA,&43,&35,275;16,&FB,&BC,5,531;16,&34,&A8,&53,787;16,&42,&85,&F4
ORIGINn,n               :REM move origin to position n,n on screen.
FORt=1TO8.256STEP1/n    :REM from 1/8 turn to 8.56 turns in small steps
  GCOL0,t-1>>1          :REM set the colours, 0=red, 1=yellow, 2=green, 3=blue
  a=t*PI/4              :REM convert angle from 1/8 turns into radians
  y=n*SIN(a)            :REM find position of outer end of ray
  x=n*COS(a)            :REM plot to coordinates of inner and outer ends of ray
  PLOT85,x*.6,y*.6      :REM PLOT85 actually draws a triangle between the specified point
  PLOT85,x,y            :REM and the last two points visited.
NEXT
PLOT101,0,-n/5          :REM once all is over, cursor is at top right corner of blue rectangle. Draw a rectangle to the bottom left corner as specified.

```

# Answer
> 21 votes
## HTML/JS, ~~680~~ 624 bytes

**To get 624 bytes, remove the last `;`, this is needed for the snippet below due to the way it imports the HTML. Also, Firefox seems to not support `image-rendering: pixelated` and needs `-moz-crisp-edges` instead (thanks @alldayremix!) which makes a Firefox solution +7 but this does work in Chrome as expected.**

Utilises JavaScript to request `N` and a `<style>` block to position/colour the elements. Uses basic HTML elements, rather than applying styles to a canvas (which, it appears, was a much shorter approach!). This is a revamped approach using a `data:` URI background image instead of just coloured elements. I've kept the previous approach below in case this new one works on fewer browsers.

I thought this was going to be a lot smaller than it ended up being, but it was an interesting exercise nonetheless!

```
<body id=x onload=x.style.fontSize=prompt()+'px'><u><a></a><b></b><i></i><s><style>u,a,b,i,s{position:relative;display:block}b,i,s{position:absolute}a,u{width:1em;height:1em}a,b{border-radius:50%}a{image-rendering:pixelated;background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAFklEQVQI12N45Wzq1PqF4fceVpMVwQAsHQYJ1N3MAQAAAABJRU5ErkJggg)no-repeat;background-size:100%;transform:rotate(45deg)}b{top:.2em;left:.2em;width:.6em;height:.6em;background:#fff}i{border-top:.4em solid transparent;border-right:.4em solid#fff;top:0;right:0}s{top:.4em;right:.1em;width:.4em;height:.2em;background:#4285f4;
```

Previous version:

```
<body id=x onload=x.style.fontSize=prompt()+'px'><a b><b l style=padding-left:.5em></b><b y></b><b g></b></a><i style=height:.4em></i><i style="background:#ea4335;border-radius:0 1em 0 0;transform-origin:0%100%;transform:rotate(-45deg)"></i><i b z style=top:.2em;left:.2em;width:.6em;height:.6em></i><i l z style="top:.4em;height:.2em;border-radius:0 2%10%0/0 50%50%0;width:.4em"><style>*{position:relative;background:#fff}a,b,i{display:block;float:left;width:.5em;height:.5em}a{height:1em;width:1em;transform:rotate(45deg);overflow:hidden}i{position:absolute;top:0;left:.5em}[b]{border-radius:50%}[g]{background:#34a853}[l]{background:#4285f4}[y]{background:#fbbc05}[z]{z-index:1
```

# Answer
> 20 votes
## Bash with Imagemagick (but really Postscript), ~~268~~ ~~255~~ 249 bytes

```
C=' setrgbcolor 2.5 2.5 2'
A=' arc stroke '
echo "%!PS
122.4 dup scale
.92 .26 .21$C 45 136$A.98 .74 .02$C 135 226$A.20 .66 .33$C 225 316$A.26 .52 .96$C 315 371$A
4.95 2.5 moveto
2.5 2.5 lineto
stroke"|convert - -crop 612x612+0+180 -scale "$1" o.png

```

Doubled the scaling to remove `setlinewidth`, replaced one scale factor with `dup`, and merged a space into the `A` variable (can't with `C` because `$C45` is parsed as "the variable `C45`").

Thanks to joojaa for suggesting these edits!

### Old Scale, 255 bytes

```
C=' setrgbcolor 5 5 4'
A=' arc stroke'
echo "%!PS
61.2 61.2 scale
2 setlinewidth
.92 .26 .21$C 45 136$A
.98 .74 .02$C 135 226$A
.20 .66 .33$C 225 316$A
.26 .52 .96$C 315 371$A
9.9 5 moveto
5 5 lineto
stroke"|convert - -crop 612x612+0+180 -scale "$1" o.png

```

Takes *N* as the lone argument and outputs to o.png.

### Ungolfed Postscript for Old Scale

```
%!PS
% Scale so default page has width of 10
61.2 61.2 scale
2 setlinewidth
% Red arc
.92 .26 .21 setrgbcolor
5 5 4 45 136 arc
stroke
% Yellow arc
.98 .74 .02 setrgbcolor
5 5 4 135 226 arc
stroke
% Green arc
.20 .66 .33 setrgbcolor
5 5 4 225 316 arc
stroke
% Blue arc
.26 .52 .96 setrgbcolor
5 5 4 315 371 arc
% Blue in-tick
9.9 5 moveto
5 5 lineto
stroke

```

# Answer
> 19 votes
# Perl 5, 486 477 476 450 (+7 for `-MImager` flag) = 457 bytes

I saved a few bytes thanks to Dada by using functional `new` calls and getting rid of parens, and by using `pop` instead of `$ARGV[0]` as well as the final semicolon. I saved some more by putting that `$n=pop` where it's first used, and by using Perl 4 namespace notation with `'` instead of `::`.

```
$i=new Imager xsize=>$n=pop,ysize=>$n;$h=$n/2;$s=$n*.6;$f=$n*.4;$c='color';($b,$r,$y,$g,$w)=map{new Imager'Color"#$_"}qw(4285f4 ea4335 fbbc05 34a853 fff);$i->box(filled=>1,$c,$w);$i->arc($c,$$_[0],r=>$h,d1=>$$_[1],d2=>$$_[2])for[$b,315,45],[$r,225,315],[$y,135,225],[$g,45,135];$i->circle($c,$w,r=>$n*.3,filled=>1);$i->box($c,$b,ymin=>$f,ymax=>$s,xmin=>$h,xmax=>$n*.9,filled=>1);$i->polygon($c,$w,x=>[$n,$n,$s],y=>[0,$f,$f]);$i->write(file=>'g.png')

```

It requires the module Imager, which needs to be installed from CPAN. Takes one integer as a command line argument. The image is not anti-aliased, so it's a bit ugly.

Copy the below code into a file g.pl. We need an additional +7 bytes for the `-MImager` flag, but it saves a few bytes because we don't need to `use Imager;`.

```
$ perl -MImager g.pl 200

```

Here are various sizes:

N=10

N=100

N=200

The completely ungolfed code is straight-forward.

```
use Imager;
my $n = $ARGV[0];
my $i = Imager->new( xsize => $n, ysize => $n );

my $blue   = Imager::Color->new('#4285f4');
my $red    = Imager::Color->new('#ea4335');
my $yellow = Imager::Color->new('#fbbc05');
my $green  = Imager::Color->new('#34a853');
my $white  = Imager::Color->new('white');

$i->box( filled => 1, color => 'white' );
$i->arc( color => $blue,   r => $n / 2, d1 => 315, d2 => 45 );     # b
$i->arc( color => $red,    r => $n / 2, d1 => 225, d2 => 315 );    # r
$i->arc( color => $yellow, r => $n / 2, d1 => 135, d2 => 225 );    # y
$i->arc( color => $green,  r => $n / 2, d1 => 45,  d2 => 135 );    # g
$i->circle( color => $white, r => $n * .3, filled => 1 );
$i->box(
    color  => $blue,
    ymin   => $n * .4,
    ymax   => $n * .6,
    xmin   => $n / 2,
    xmax   => $n * .9,
    filled => 1
);
$i->polygon( color => $white, x => [ $n, $n, $n * .6 ], y => [ 0, $n * .4, $n * .4 ] );
$i->write( file => 'g.png' );

```

---

This post previously had the code shaped like the output image. Since that is against the rules for code golf I had to remove it. See the revision history if you want to take a look. I used Acme::EyeDrops to create that, with a shape that I created from an image created with the program itself that I converted to ASCII art. The code I obfuscated was already golfed, which can be seen by replacing the first `eval` with a `print`.

# Answer
> 19 votes
# MATLAB, ~~189~~ 184 bytes

```
[X,Y]=meshgrid(-5:10/(input("")-1):5);[A,R]=cart2pol(-X,Y);I=round(A*2/pi+3);I(R<3)=1;I(X>0&Y.^2<1)=5;I(R>5)=1;image(I)
colormap([1,1,1;[234,67,53;251,188,5;52,168,83;66,133,244]/255])

```

## ungolfed

```
[X,Y]=meshgrid(-5:10/(input("")-1):5);    % coordinates in 10th of image width
[A,R]=cart2pol(-X,Y);                     % angle and radius
I=round(A*2/pi+3); % map [0-45,45-135,135-225,225-315,315-360] to [1,2,3,4,5]
I(R<3)=1;                                 % clear inner pixels
I(X>0&Y.^2<1)=5;                          % draw horizontal line
I(R>5)=1;                                 % clear outer pixels
image(I)
colormap([1,1,1;[234,67,53;251,188,5;52,168,83;66,133,244]/255])

```

# Answer
> 14 votes
# PHP + SVG, 300 Bytes

```
<svg width=<?=$_GET["w"]?> viewBox=0,0,10,10><def><path id=c d=M0,5A5,5,0,0,1,5,0V2A3,3,0,0,0,2,5 /></def><?foreach(["fbbc05"=>-45,"ea4335"=>45,"4285f4"=>168.5,"34a853"=>225]as$k=>$v)echo"<use xlink:href=#c fill=#$k transform=rotate($v,5,5) />"?><rect x=5 y=4 fill=#4285f4 width=4.9 height=2 /></svg>

```

The scaling part is `width=<?=$_GET[w]?>`

Output for value 333

```
<svg width="333" viewBox="0 0 10 10">
<def><path id="c" d="M 0,5 A 5 5 0 0 1 5,0 V 2 A 3,3 0 0 0 2,5"/></def>
<use xlink:href="#c" fill="#fbbc05" transform="rotate(-45,5,5)"/><use xlink:href="#c" fill="#ea4335" transform="rotate(45,5,5)"/><use xlink:href="#c" fill="#4285f4" transform="rotate(168.5,5,5)"/><use xlink:href="#c" fill="#34a853" transform="rotate(225,5,5)"/>
<rect x="5" y="4" fill="#4285f4" width="4.9" height="2"/>
</svg>
```

# Answer
> 14 votes
# Logo, 258 bytes

... because I figure **logos should be made using Logo**. This is implemented as a function. I developed it using Calormen.com's online Logo interpreter

I originally attempted to draw each segment and paint fill it, but that turned out to be bigger than expected. There was a lot of wasted movement backtracking and such. Instead, I decided to do a polar graph sweep, adjusting the color based on the heading. The harder part of the math was doing the geometry for the curve at the top of the G's rectangle. You could trim some decimals and have less accuracy, but I wanted this to be accurate to about 3 digits to accommodate typical screen sizes.

## Golfed

```
to g:n
ht
make"a arctan 1/:n
seth 78.46
repeat 326.54/:a[make"h heading
pu fd:n/2 pd
setpc"#4285f4
if:h>135[setpc"#34a853]if:h>225[setpc"#fbbc05]if:h>315[setpc"#ea4335]bk:n*.2 pu bk:n*.3
rt:a]home bk:n*.1
filled"#4285f4[fd:n/5 rt 90 fd:n*.49 rt 90 fd:n/5]end

```

## Sample

`g 200`

## Ungolfed

```
to g :n ; Draw a G of width/height n

hideturtle ; Hide the turtle, since she's not part of the Google logo

;Determine the proper size of the angle to rotate so that the circle stays smooth within 1 px at this size
make "a arctan 1/:n

setheading 78.46 ; Point toward the top corner of the upcoming rectangle

repeat 326.54 / :a [ ; Scoot around most of the circle, :a degrees at a time

  make"h heading ; Store heading into a variable for golfing purposes

  ; Position pen at the next stroke
  penup
  forward :n / 2
  pendown

  ; Set the pen color depending on the heading
  setpencolor "#4285f4
  if :h > 135 [ setpencolor "#34a853]
  if :h > 225 [ setpencolor "#fbbc05]
  if :h > 315 [ setpencolor "#ea4335]

  ; Draw the stroke and return to center
  back :n * .2
  penup
  back :n * .3

  right :a ; Rotate to the next sweep heading
]

; Draw the rectangle
home
back :n * .1
filled "#4285f4 [
  forward :n/5
  right 90
  forward :n * .49 ;This is just begging to be :n / 2 but I couldn't bring myself to do it.  Proper math is more like :n * (sqrt 6) / 5
  right 90
  forward :n / 5
]

end

```

# Answer
> 12 votes
## JavaScript (ES7), ~~285~~ ~~258~~ ~~254~~ ~~252~~ 251 bytes

Prompts for the width of the logo (up to 999) and draws it in a canvas, pixel per pixel.

***Edit****: The initial version was converting Cartesian coordinates `(x,y)` to Polar coordinates `(r,a)`, but we don't really need the angle. It's simpler (and significantly shorter) to just do comparisons between `x` and `y` to find out in which quarter we are.*

***Edit****: Saved 1 byte thanks to ETHproductions.*

### JS, ~~251~~ ~~224~~ ~~220~~ ~~218~~ 217 bytes

```
for(w=x=y=prompt(c=c.getContext`2d`)/2;r=(x*x+y*y)**.5,q=(x<y)+2*(x<-y),c.fillStyle='#'+'4285F434A853EA4335FBBC05FFF'.substr(x>0&r<w&y*y<w*w/25?0:r<w*.6|r>w|!q&y<0?24:q*6,6),x-->-w||y-->-(x=w);)c.fillRect(x+w,y+w,1,1)

```

### HTML, 34 bytes

```
<canvas id=c width=999 height=999>

```

### ES6 version: ~~258~~ ~~231~~ ~~227~~ ~~225~~ 224 + 34 = 258 bytes

Recommended maximum width for the snippet: 190.

```
for(w=x=y=prompt(c=c.getContext`2d`)/2;r=Math.pow(x*x+y*y,.5),q=(x<y)+2*(x<-y),c.fillStyle='#'+'4285F434A853EA4335FBBC05FFF'.substr(x>0&r<w&y*y<w*w/25?0:r<w*.6|r>w|!q&y<0?24:q*6,6),x-->-w||y-->-(x=w);)c.fillRect(x+w,y+w,1,1)
```

```
<canvas id=c width=999 height=999>
```

# Answer
> 11 votes
## ~~JS/~~CSS/HTML(+JS), ~~40~~ 0 + ~~701~~ ~~644~~ ~~617~~ 593 + ~~173~~ ~~90~~ ~~97 121 = ~~914~~ ~~774~~ ~~754~~ 730~~ 714 bytes

```
*{position:absolute}a,h{height:100%;background:#4285F4}a,g{width:100%;border-radius:100%}h{width:30%;height:20%;top:40%}b,c,d,e,f{width:50%;height:50%}b,d,f,h{left:50%}e,f{top:50%}c{border-radius:100% 0 0;background:linear-gradient(45deg,#FBBC05 50%,#EA4335 50%)}d{border-radius:0 100% 0 0;background:linear-gradient(-45deg,transparent 50%,#EA4335 50%)}e{border-radius:0 0 0 100%;background:linear-gradient(-45deg,#34A853 50%,#FBBC05 50%)}f{border-radius:0 0 100%;background:linear-gradient(45deg,#34A853 50%,#4285F4 50%)}b,g{height:40%;background:#FFF}g{width:60%;height:60%;top:20%;left:20%}
```

```
<input oninput=with(o.style)height=width=value+"px"><o id=o><a></a><b></b><c></c><d></d><e></e><f></f><g></g><h></h></o>
```

Uses linear gradients rather than transforms. Edit: Saved 140 bytes thanks to @darrylyeo. Saved 20 bytes by using an extra element instead of a gradient. Saved 24 bytes thanks to @DBS. Saved 16 bytes thanks to @Hedi. From back to front, the various layers are:

* `a` The blue circle
* `b` A white rectangle to obscure the part above the bar
* `c` The red/yellow top left quarter
* `d` The red octant top right
* `e` The yellow/green bottom left quarter
* `f` The green/blue bottom right quarter
* `g` The inner white circle
* `h` The horizontal blue bar

## JavaScript (ES6) (+SVG), 293 bytes, invalid

```
document.write(`<svg id=o width=${prompt()} viewbox=0,0,50,50>`);m=`39,11`;`#EA433511,11
#FBBC0511,39
#34A85339,39
#4285F445,25L25,25`.replace(/(.{7})(.{5})(.*)/g,(_,s,t,u)=>m=document.write(`<path stroke=${s} d=M${m}A20,20,0,0,0,${t+u} fill=none stroke-width=10 stroke-linejoin=round />`)||t)
```

Sadly the round line join isn't quite the requested effect, but it's pretty close.

# Answer
> 11 votes
# C#, 276 + 21 = 297 bytes

276 bytes for method + 21 bytes for System.Drawing import.

```
using System.Drawing;n=>{var q=new Bitmap(n,n);uint W=0xFFFFFFFF,B=0xFF4285F4;for(int y=0,x=0;x<n;y=++y<n?y:x-x++){float a=2f*x/n-1,b=2f*y/n-1,c=b*b;q.SetPixel(x,y,Color.FromArgb((int)(a>0&&a<.8&&c<.04?B:a*a+c>1||a*a+c<.36?W:a*a<c?b<0?0xFFEA4335:0xFF34A853:a<0?0xFFFBBC05:b<-.2?W:B)));}return q;};

```

Based on Martin Rosenau's algorithm. Thanks for doing the hard part of coming up with a way to construct the image!

```
using System.Drawing;             // Import System.Drawing
/*Func<int, Bitmap>*/ n =>
{
    var q = new Bitmap(n, n);     // Create nxn output bitmap
    uint W=0xFFFFFFFF,            // White, color used more than once
         B=0xFF4285F4;            // Blue, color used more than once
    for(int y = 0, x = 0; x < n;  // Loops for(x=0;x<N;x+=1) for(y=0;y<N;y+=1) combined
        y = ++y < n               // Increment y first until it reaches n
            ? y
            : x - x++)            // Then increment x, resetting y
    {
        float a = 2f * x / n - 1, // Relative coords. Refer to Martin Rosenau's
              b = 2f * y / n - 1, // for what this magic is.
              c = b * b;          // b*b is used more than 3 times

        q.SetPixel(x, y,          // Set pixel (x,y) to the appropriate color
            Color.FromArgb((int)  // Cast uint to int :(
            ( // Here lies magic
                a > 0 && a < .8 && c < .04
                    ? B
                    : a * a + c > 1 || a * a + c < .36
                        ? W
                        : a * a < c
                            ? b < 0
                                ? 0xFFEA4335
                                : 0xFF34A853
                            : a < 0
                                ? 0xFFFBBC05
                                : b < -.2
                                    ? W
                                    : B
            )));
    }
    return q;
};

```

26:

400:

# Answer
> 8 votes
## Ruby 2.3.1, 376 359 bytes

Using the RMagick gem.

```
d,f=$*[0].to_i,2.5;g,h,e,c=d-1,d/2,Magick::ImageList.new,Magick::Draw.new;e.new_image(d,d);c.stroke('#EA4335').fill_opacity(0).stroke_width(d*0.2).ellipse(h,h,g/f,g/f,225,315).stroke('#FBBC05').ellipse(h,h,g/f,g/f,135,225).stroke('#34A853').ellipse(h,h,g/f,g/f,45,135).stroke('#4285F4').ellipse(h,h,g/f,g/f,348.5,45).line(h,h,d*0.989,h).draw(e);e.write($*[1])

```

**Examples**

50x50

250x250

500x500

1000x1000

File takes two parameters- the first being the dimension and the second being the filename to save the output as.

**Ungolfed**

```
require "RMagick"

# Take the user's input for dimension
d = $*[0].to_i

e = Magick::ImageList.new
e.new_image(d, d)

c = Magick::Draw.new

# Start by setting the color to red
c.stroke('#EA4335')

  # set opacity to nothing so that we don't get extra color.
  .fill_opacity(0)

  # set thickness of line.
  .stroke_width(d*0.2)

  # #ellipse creates an ellipse taking
  # x, y of center
  # width, height,
  # arc start, arc end
  .ellipse(d / 2, d / 2, (d - 1) / 2.5, (d - 1) / 2.5, 225, 315)

  # change to yellow and draw its portion
  .stroke('#FBBC05')
  .ellipse(d / 2, d / 2, (d - 1) / 2.5, (d - 1) / 2.5, 135, 225)

  # change to green and draw its portion
  .stroke('#34A853')
  .ellipse(d / 2, d / 2, (d - 1) / 2.5, (d - 1) / 2.5, 45, 135)

  # change to blue and draw its portion
  .stroke('#4285F4')
  .ellipse(d / 2, d / 2, (d-1)/2.5, (d - 1)/2.5, 348.5, 45)

  # creates the chin for the G
  .line(d/2, d/2, d*0.99, d/2)

  # draws to the created canvas
  .draw(e)

# save out the file
# taking the filename as a variable saves a byte over
# "a.png"
e.write($*[1])

```

I had initially started solving this using oily\_png/chunky\_png but that would likely end up far too complicated compared to RMagick. RMagick's .ellipse function made this a breeze and the main work was around tuning the shapes/sizes of everything.

This is my first Code Golf submission(first SE answer also) and I only consider myself somewhat intermediate with Ruby. If you have any input on improvement/tips, please feel free to share!

# Answer
> 5 votes
# Python 2, ~~378~~ 373 bytes

I really wanted to do this using `turtle`. I had to dust off my knowledge of Geometry for this, calculating angles and lengths not provided in the challenge description.

*Edit: removed `up()`, since doing so removes the little sliver of white between green and blue and makes the inner circle look better. This slows down the program even more.*

*Edit: replaced `9*n` with `2*n` to make faster. I determined that it would still create a smooth circle.*

```
from turtle import*
n=input()
C=circle
F=fill
K=color
q=90
w="white"
t=n*.3
lt(45)
def P(c,x,A):K(c);F(1);fd(x);lt(q);C(x,A,2*n);F(0);goto(0,0);rt(q)
for c in"#EA4335","#FBBC05","#34A853":P(c,n/2,q)
P(w,t,360)
K("#4285F4")
F(1)
fd(n/2)
lt(q)
a=11.537
C(n/2,45+a,2*n)
seth(0)
bk(.489*n)
rt(q)
fd(n/5)
lt(q)
fd(t)
F(0)
bk(t)
K(w)
F(1)
fd(.283*n)
lt(94-2*a)
C(t,a-45,2*n)
F(0)

```

**Notes:**

1. The trinkets use Python 3, so the input must be cast to int.
2. The trinkets go *really* slow for large `n` if you remove `speed(0)`, which I added only for speed.
3. The slowness of the code is mostly due to the third parameter of `circle` growing `O(n)`, since it determines how many sides the inscribed polygon for drawing the circle has.

**Try it online**

**Ungolfed:** **Try it online**

**Fun fact:** `Trinket` is an anagram of `Tkinter`, Python's GUI package and the foundation for `turtle`.

# Answer
> 5 votes
# PHP + GD, ~~529~~ 449 bytes

This takes a query string parameter `n` and outputs a PNG version of the logo of the specified size.

```
<?php $n=$_GET['n'];$h=$n/2;$c='imagecolorallocate';$a='imagefilledarc';$i=imagecreatetruecolor($n,$n);$m=[$c($i,66,133,244),$c($i,52,168,83),$c($i,251,188,5),$c($i,234,67,53),$c($i,255,255,255)];imagefill($i,0,0,$m[4]);$j=-11.6;foreach([45,135,225,315]as$k=>$e){$a($i,$h,$h,$n,$n,$j,$e,$m[$k],0);$j=$e;}$a($i,$h,$h,$n*.6,$n*.6,0,0,$m[4],0);imagefilledrectangle($i,$h,$h-$n*.1,$h+$h*.98,$h+$h*.2,$m[0]);header('Content-Type:image/png');imagepng($i);

```

Ungolfed:

```
<?php

$n = $_GET['n'];$h=$n/2;
$c = 'imagecolorallocate';$a='imagefilledarc';
$i = imagecreatetruecolor($n,$n);

// Create array of colors
$m=[$c($i,66,133,244),$c($i,52,168,83),$c($i,251,188,5),$c($i,234,67,53),$c($i,255,255,255)];

// Fill background with white
imagefill($i, 0, 0, $m[4]);

// Create four arcs
$j=-11.6;
foreach([45,135,225,315]as$k=>$e){
    $a($i, $h, $h, $n, $n, $j, $e, $m[$k], 0);$j=$e;
}

// Hollow out the center and fill with white
$a($i, $h, $h, $n*.6,$n*.6,0,0,$m[4],0);

// create the horizontal bar
imagefilledrectangle($i,$h,$h-$n*.1,$h+$h*.98,$h+$h*.2,$m[0]);

// Output
header('Content-Type: image/png');
imagepng($i);

```

N=13:

N=200:

# Answer
> 5 votes
# Java, 568 bytes

Not the strongest language for golfing, but here is my earnest attempt:

```
import java.awt.image.*;class G{public static void main(String[]b)throws Exception{int n=Integer.parseInt(b[0]),x,y,a,c;BufferedImage p=new BufferedImage(n,n,BufferedImage.TYPE_INT_RGB);for(y=0;y<n;y++){for(x=0;x<n;x++){double u=(x+.5)/n-.5,v=.5-(y+.5)/n,r=Math.hypot(u,v);a=(int)(Math.atan2(v,u)*4/Math.PI);c=0xFFFFFF;if(0<u&u<.4&-.1<v&v<.1)c=0x4285F4;else if(r<.3|r>.5);else if(a==0&v<.1)c=0x4285F4;else if(a==1|a==2)c=0xEA4335;else if(a==-1|a==-2)c=0x34A853;else if(a!=0)c=0xFBBC05;p.setRGB(x,y,c);}}javax.imageio.ImageIO.write(p,"png",new java.io.File("G.png"));}}

```

Usage:

```
> javac G.java
--> Compiles to G.class
> java G 400
--> Writes G.png in current working directory

```

Un-golfed version - the basic idea is to work in the coordinate system u, v ∈ \[−0.5, 0.5\] and calculate the distance and angle of each pixel from the image center:

```
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Google {

    public static void main(String[] args) throws IOException {
        int n = Integer.parseInt(args[0]);
        int[] pixels = new int[n * n];

        for (int y = 0; y < n; y++) {
            for (int x = 0; x < n; x++) {
                double u = (x + 0.5) / n - 0.5;
                double v = 0.5 - (y + 0.5) / n;
                double r = Math.hypot(u, v);
                int a = (int)(Math.atan2(v, u) * 4 / Math.PI);
                int c = 0xFFFFFF;
                if (0 < u && u < 0.4 && Math.abs(v) < 0.1)
                    c = 0x4285F4;
                else if (r < 0.3 || r > 0.5)
                    /*empty*/;
                else if (a == 0 && v < 0.1)
                    c = 0x4285F4;
                else if (a == 1 || a == 2)
                    c = 0xEA4335;
                else if (a == -1 || a == -2)
                    c = 0x34A853;
                else if (a != 0)
                    c = 0xFBBC05;
                pixels[y * n + x] = c;
            }
        }

        BufferedImage image = new BufferedImage(n, n, BufferedImage.TYPE_INT_RGB);
        image.setRGB(0, 0, n, n, pixels, 0, n);
        ImageIO.write(image, "png", new File("G.png"));
    }

}

```

My implementation computes and draws raw pixels. It is possible to create an alternative implementation that uses high-level graphics routines like Graphics2D and Arc2D to do the drawing, especially with anti-aliasing.

# Answer
> 5 votes
# CJam, 141

```
ri:M.5*:K5/:T;'P3NMSMN255NM2m*[K.5-_]f.-{:X:mh:IK>0{X~0<\zT>|{IT3*<0{X~>X~W*>:Z2+{Z{X0=TW*>}4?}?}?}1?}?}%"^^G_8:nEhB%P9IW@zA"102b256b3/f=:+N*

```

Try it online

Outputs the image in ASCII ppm format.
For an ASCII-art version that's nicer to look at in the browser, try this code. It helps visualize the algorithm too.

**Explanation:**

```
ri:M                 read input, convert to int and store in M
.5*:K                multiply by 0.5 and store in K (M/2)
5/:T;                divide by 5 and store in T (M/10) and pop
'P3NMSMN255N         ppm header (N=newline, S=space)
M2m*                 generate all pixel coordinates - pairs of numbers 0..M-1
[K.5-_]              push the center (coordinates K-0.5, K-0.5)
f.-                  subtract the center from every pixel
{…}%                 map (transform) the array of coordinate pairs
  :X                 store the current pair in X
  :mh:I              calculate the hypotenuse of X (distance from the center)
                      and store in I
  K>0                if I>K (outside the big circle), push 0
  {…}                else…
    X~               dump X's coordinates (row, column)
    0<               check if the column is <0
    \zT>|            or the absolute value of the row is >T
    {…}              if true (outside the G bar)…
      IT3*<0         if I<T*3 (inside the small circle) push 0
      {…}            else (between the circles)…
        X~>          dump X and check if row>column (diagonal split)
        X~W*>:Z      also check if row>-column (other diagonal) and store in Z
                      (W=-1)
        2+           if in lower-left half, push Z+2 (2 for left, 3 for bottom)
        {…}          else (upper-right half)…
          Z{…}       if it's in the right quadrant
            X0=      get the row coordinate of X
            TW*>     compare with -T, resulting in 0 (above the bar) or 1
          4          else (top quadrant) push 4
          ?          end if
        ?            end if
      ?              end if
    1                else (inside the G bar) push 1
    ?                end if
  ?                  end if
"^^G … @zA"          push a string containing the 5 colors encoded
102b                 convert from base 102 to a big number
                      (ASCII values of chars are treated as base-102 digits)
256b                 convert to base 256, splitting into 15 bytes
3/                   split into triplets (RGB)
f=                   replace each generated number (0..4)
                      with the corresponding color triplet
:+N*                 join all the triplets, and join everything with newlines

```

# Answer
> 4 votes
## Go, 379 bytes

```
import ."fmt"
func f(a int)(s string){
m:=map[string]float64{"fbbc05":-45,"ea4335":45,"4285f4":168.5,"34a853":225}
for k,v:=range m{s+=Sprintf("<use xlink:href=#c fill=#%v transform=rotate(%v,5,5) />",k,v)}
return Sprintf("<svg width=%v viewBox=0,0,10,10><def><path id=c d=M0,5A5,5,0,0,1,5,0V2A3,3,0,0,0,2,5 /></def>%v<rect x=5 y=4 fill=#4285f4 width=4.9 height=2 /></svg>",a,s)}

```

The function `f` takes a single `int` argument (the scale factor) and outputs an SVG image scaled appropriately.

Try it online at Ideone.

Example output:

```
<svg width=333 viewBox=0,0,10,10><def><path id=c d=M0,5A5,5,0,0,1,5,0V2A3,3,0,0,0,2,5 /></def><use xlink:href=#c fill=#34a853 transform=rotate(225,5,5) /><use xlink:href=#c fill=#fbbc05 transform=rotate(-45,5,5) /><use xlink:href=#c fill=#ea4335 transform=rotate(45,5,5) /><use xlink:href=#c fill=#4285f4 transform=rotate(168.5,5,5) /><rect x=5 y=4 fill=#4285f4 width=4.9 height=2 /></svg>
```

It seems wrong to appease our Google overlords in any programming language except their own.

# Answer
> 3 votes
# FreeMarker+HTML/CSS, 46 + 468 = 514 bytes

HTML:

```
<div><div></div><div></div><span></span></div>

```

CSS:

```
div div,div span{position:absolute}div{width:10px;height:10px;box-sizing:border-box;transform-origin:top left;position:relative;transform:scale(${n*.1})}div div{border:2px solid;border-radius:9px;border-color:transparent #4285f4 transparent transparent;transform:rotate(33.4630409671deg);transform-origin:center}div div+div{border-color:#ea4335 transparent #34a853 #fbbc05;transform:none}div span{display:block;top:4px;bottom:4px;left:5px;right:.1px;background:#4285f4}

```

Assuming the FreeMarker processor is executed with a variable `n` set, representing input.

## Explanation of magic numbers:

Everything is based on a 10x10px wrapper, then scaled by `n/10`.

* Distance to right of blue horizontal box \[px\]: 5 - sqrt(5^2 - 1^2) = **0.10102051443** (Pythagoras)
* Rotation of blue arc \[deg\]: 45 - arcSin(1/5) = **33.4630409671** (Sine)

## Ungolfed JSFiddle

# Answer
> 3 votes
# 343 octets of Haskell

```
roman@zfs:~$ cat ppmG.hs
ppmG n='P':unlines(map show([3,n,n,255]++concat[
 case map signum[m^2-(2*x-m)^2-(2*y-m)^2,
 (10*x-5*m)^2+(10*y-5*m)^2-(3*m)^2,
 m-x-y,x-y,5*y-2*m,3*m-5*y,2*x-m]of
 1:1:1:1:_->[234,67,53]
 1:1:1:_->[251,188,5]
 [1,_,_,_,1,1,1]->[66,133,244]
 1:1:_:1:1:_->[66,133,244]
 1:1:_:_:1:_->[52,168,83]
 _->[255,255,255]|m<-[n-1],y<-[0..m],x<-[0..m]]))
roman@zfs:~$ wc ppmG.hs
 10  14 343 ppmG.hs
roman@zfs:~$ ghc ppmG.hs -e 'putStr$ppmG$42'|ppmtoxpm
ppmtoxpm: (Computing colormap...
ppmtoxpm: ...Done.  5 colors found.)

/* XPM */
static char *noname[] = {
/* width height ncolors chars_per_pixel */
"42 42 6 1",
/* colors */
"  c #4285F4",
". c #EA4335",
"X c #FBBC05",
"o c #34A853",
"O c #FFFFFF",
"+ c None",
/* pixels */
"OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO",
"OOOOOOOOOOOOOOO............OOOOOOOOOOOOOOO",
"OOOOOOOOOOOO..................OOOOOOOOOOOO",
"OOOOOOOOOO......................OOOOOOOOOO",
"OOOOOOOOO........................OOOOOOOOO",
"OOOOOOOO..........................OOOOOOOO",
"OOOOOOO............................OOOOOOO",
"OOOOOOXX..........................OOOOOOOO",
"OOOOOXXXX........................OOOOOOOOO",
"OOOOXXXXXX.......OOOOOOOO.......OOOOOOOOOO",
"OOOXXXXXXXX....OOOOOOOOOOOO....OOOOOOOOOOO",
"OOOXXXXXXXXX.OOOOOOOOOOOOOOOO.OOOOOOOOOOOO",
"OOXXXXXXXXXXOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO",
"OOXXXXXXXXXOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO",
"OOXXXXXXXXXOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO",
"OXXXXXXXXXOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO",
"OXXXXXXXXXOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO",
"OXXXXXXXXOOOOOOOOOOOO                    O",
"OXXXXXXXXOOOOOOOOOOOO                    O",
"OXXXXXXXXOOOOOOOOOOOO                    O",
"OXXXXXXXXOOOOOOOOOOOO                    O",
"OXXXXXXXXOOOOOOOOOOOO                    O",
"OXXXXXXXXOOOOOOOOOOOO                    O",
"OXXXXXXXXOOOOOOOOOOOO                    O",
"OXXXXXXXXOOOOOOOOOOOO                    O",
"OXXXXXXXXXOOOOOOOOOOOOOOOOOOOOOO         O",
"OXXXXXXXXXOOOOOOOOOOOOOOOOOOOOOO         O",
"OOXXXXXXXXXOOOOOOOOOOOOOOOOOOOO         OO",
"OOXXXXXXXXXOOOOOOOOOOOOOOOOOOOO         OO",
"OOXXXXXXXXXXOOOOOOOOOOOOOOOOOO          OO",
"OOOXXXXXXXXooOOOOOOOOOOOOOOOOoo        OOO",
"OOOXXXXXXXoooooOOOOOOOOOOOOooooo       OOO",
"OOOOXXXXXooooooooOOOOOOOOoooooooo     OOOO",
"OOOOOXXXoooooooooooooooooooooooooo   OOOOO",
"OOOOOOXoooooooooooooooooooooooooooo OOOOOO",
"OOOOOOOooooooooooooooooooooooooooooOOOOOOO",
"OOOOOOOOooooooooooooooooooooooooooOOOOOOOO",
"OOOOOOOOOooooooooooooooooooooooooOOOOOOOOO",
"OOOOOOOOOOooooooooooooooooooooooOOOOOOOOOO",
"OOOOOOOOOOOOooooooooooooooooooOOOOOOOOOOOO",
"OOOOOOOOOOOOOOOooooooooooooOOOOOOOOOOOOOOO",
"OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO"
};

```

## Explanation

* "P3" == plaintext portable pixmap
* show == produce ASCII decimals fearing UTF-8 corruption for "\xFF\xFF\xFF"
* unlines == separate decimals into lines
* m = n-1 for symmetry in n==length\[0..m\]
* m²-(2x-m)²-(2y-m)²\>0 == (x-m/2)² + (y-m/2)² \< (m/2)² == insideOuterCircle
* (10x-5m)²+(10y-5m)²-(3m)²\>0 == (x-m/2)² + (y-m/2)² \> (m3/10)² == outsideInnerCircle
* m-x-y\>0 == x+y \< m == inUpperLeft
* x-y\>0 == x \> y == inUpperRight
* 5y-2m\>0 == y \> m2/5 == belowGbarTop
* 3y-5y\>0 == y \< m3/5 == aboveGbarBot
* 2x-m\>0 == x \> m/2 == inRightHalf
* \[234,67,53\] == red
* \[251,188,5\] == yellow
* \[52,168,83\] == green
* \[66,13,244\] == blue
* \[255,255,255\] == white

# Answer
> 3 votes
# SAS - ~~590~~ ~~536~~ 521 bytes

This uses the GTL Annotation facility. Input is specified in a macro variable on the first line. For a few extra bytes you can define the whole thing as a macro. It still sneaks in below Java and a few of the HTML answers, even though you have to define a null graph template just to be able to plot anything at all!

I've left the line breaks in for a modicum of readability, but I'm not counting those towards the total as it works without them.

```
%let R=;
%let F=FILLCOLOR;
ods graphics/width=&R height=&R;
proc template;
define statgraph a;
begingraph;
annotate;
endgraph;
end;
data d;
retain FUNCTION "RECTANGLE" DISPLAY "FILL" DRAWSPACE "graphPERCENT";
length &F$8;
_="CX4285F4";
P=100/&R;
HEIGHT=P;
width=P;
do i=1to &R;
x1=i*P;
U=x1-50;
do j=1to &R;
y1=j*P;
V=y1-50;
r=euclid(U,V);
&F="";
if 30<=r<=50then if V>U then if V>-U then &F="CXEA4335";
else &F="CXFBBC05";
else if V<-U then &F="CX34A853";
else if V<10then &F=_;
if &F>'' then output;
end;
end;
x1=65;
y1=50;
width=30;
height=20;
&F=_;
output;
proc sgrender sganno=d template=a;

```

**Edit:** shaved off a few more bytes via use of macro vars, default settings and choice of operators.

**Edit 2:** got rid of the `do-end` blocks for the `if-then-else` logic and it somehow still works - I don't entirely understand how. Also, I discovered the `euclid` function!

# Answer
> 2 votes
# SCSS - 415 bytes

Takes input as `$N: 100px;` and `<div id="logo"></div>`, not sure if these should count in the total though...

```
$d:$N*.6;$b:$d/3;#logo{width:$d;height:$d;border:$b solid;border-color:#ea4335 transparent #34a853 #fbbc05;border-radius:50%;position:relative;&:before,&:after{content:'';position:absolute;right:-$b;top:50%;border:0 solid transparent}&:before{width:$b*4;height:$d/2;border-width:0 $b $b 0;border-right-color:#4285f4;border-bottom-right-radius:50% 100%}&:after{width:$N/2;margin:-$b/2 0;border-top:$b solid #4285f4}}

```

Demo on JSFiddle

# Answer
> 1 votes
# Haskell with JuicyPixels package, 306 bytes

```
import Codec.Picture
p=PixelRGB8
c=fromIntegral
b=p 66 133 244
w=p 255 255 255
(n%x)y|y<=x,x+y<=n=p 234 67 53|y>x,x+y<=n=p 251 188 5|y>x,x+y>n=p 52 168 83|y>=0.4*n=b|1>0=w
(n#x)y|d<=h,d>=0.3*n=n%x$y|x>=h,d<=h,abs(y-h)<=n/10=b|1>0=w where h=n/2;d=sqrt$(x-h)^2+(y-h)^2
f n=generateImage(\x y->c n#c x$c y)n n

```

Usage example:

```
main = writePng "google.png" $ f 1001

```

This could probably be improved. The idea is to pass a function to `generateImage` that selects the pixel (color really) that should go at position x, y. For that we use a lambda that adds `n` as a parameter and converts them all to floats at the same time. The `#` function basically checks if we're in the ring, the bar, or neither. If it's the ring we pass the baton to `%`, if the bar we just return blue, otherwise white. `%` checks which quadrant we're in and returns the appropriate color if it isn't blue. Blue is a special case since we need to make sure it doesn't wrap around to the red, so we only return blue if `y` is below the "bar line" otherwise we return white. That's the general overview.

# Answer
> 1 votes
# JavaScript + HTML, 241 bytes

228 bytes for JavaScript + 13 bytes for HTML

```
(
// code start
n=>{with(c.getContext`2d`)['#4285f4','#34a853','#fbbc05','#ea4335'].map((c,i)=>{beginPath(fillStyle=strokeStyle=c,lineWidth=n/5,a=Math.PI/2);arc(h=n/2,h,r=n*.4,j=i*a-a/2,j+a);stroke();i||clearRect(0,0,n,r)+fillRect(h,r,r,n/5)})}
// code end
)(100);
```

```
<canvas id=c>
```

# Answer
> 0 votes
# Processing.py - 244 bytes + 1 byte for number of digits in N

Let's start with the code. This can be pasted in the Processing environment and ran (changing `N` for different sizes).

```
N=400
n=N/2
f=fill
a=['#34A853','#FBBC05','#EA4335','#4285F4']
def setup():
 size(N,N);noStroke()
def draw():
 for i in 1,3,5,7: f(a[i/2]);arc(n,n,N,N,i*PI/4+[0,.59][i>6],(i+2)*PI/4)
 f(205);ellipse(n,n,.6*N,.6*N);f(a[3]);rect(n,n-.1*N,.98*n,.2*N)

```

Small cheat: the circle that *cut's out* a part from the logo is drawn in Processing's grayscale shade 205, which is the default background color. Exporting this to an image wouldn't look the same. This saves a call to `background(255)`.

### Explanation

```
N=400                 # set size
n=N/2                 # precompute center point
f=fill                # 3 usages, saves 3 bytes
a=['#34A853','#FBBC05','#EA4335','#4285F4']
                      # list of colors
def setup():          # called when starting sketch
 size(N,N)            # set size
 noStroke()           # disable stroking
def draw():           # drawing loop
 for i in 1,3,5,7:    # loop over increments of PI/4
  f(a[i/2])           # set fill color using integer
                      # division
  arc(n,n,N,N,i*PI/4+[0,.59][i>6],(i+2)*PI/4)
                      # draw a pizza slice between
                      # two coordinates. The
                      #     [0,.59][i>6]
                      # accounts for the white part
 f(205)               # set fill color to Processing's
                      # default background
 ellipse(n,n,.6*N,.6*N)
                      # cut out center
 f(a[3])              # set fill to blue
 rect(n,n-.1*N,.98*n,.2*N)
                      # draw the straight part

```

## Examples

`N` = 400

`N` = 13 (Processing's minimum size is 100x100)

## Note

If we allow us to manually edit in multiple values for `N` the explicit calls to `setup` and `draw` are not needed and it is down to 213 bytes + 3 bytes per digit in `N`.

```
N=200
size(200,200)
n=N/2
f=fill
a=['#34A853','#FBBC05','#EA4335','#4285F4']
noStroke()
for i in 1,3,5,7:f(a[i/2]);arc(n,n,N,N,i*PI/4+[0,.59][i>6],(i+2)*PI/4)
f(205);ellipse(n,n,.6*N,.6*N);f(a[3]);rect(n,n-.1*N,.98*n,.2*N)

```

---
Tags: code-golf, kolmogorov-complexity, graphical-output, geometry
---


# Question
Title: Safe bidirectional array index navigation
# Introduction

Arrays are usually used with for-loops or iterators. One different task might be the use as a cheap way to rotate through a set of items, so after reaching the last index, the next item would be the first item of the array. This is useful for cases like menus and physical controls.

# Challenge

Given the size of an array, the initial index, and the movement (which can be positive, zero, or negative), output the resulting index in the array after cyclically moving through it.

As soon as a number which is greater than the current array index `+` the number of remaining indices, the added index would go out of bounds. The other way arround, substracting a greater negative value than the current index from itself, the index would be negative and therefore invalid. This should be compensated by the solution. Also, when exceeding the index by not only one, but two or more array lengths, this should also be compensated (see example 2).

# Example input and output

> We assume (for the sake of simplicity) that arrays start at `0`.
>
> Array for visualization: `['a', 'b', 'c', 'd', 'e', 'f']`

### Example 1

**Input:**

Array size: `6`

Current Index: `1` (-\> `'b'`)

Movement: `+5`

**Index Movement:**

`2` -\> `3` -\> `4` -\> `5` -\> `0`

**Output:**

Index: `0` (-\> `'a'`)

### Example 2

**Input:**

Array size: `6`

Current Index: `2` (-\> `'c'`)

Movement: `-10`

**Index Movement:**

`1` -\> `0` -\> `5` -\> `4` -\> `3` -\> `2` -\> `1` -\> `0` -\> `5` -\> `4`

**Output:**

Index: `4` (-\> `'e'`)

# Objective

The solution with the fewest bytes wins the challenge. Using Lists, Linked Lists etc. is not allowed, fixed arrays only. Non-codegolfing languages are preferred.

# Answer
> 5 votes
# APL (Dyalog Unicode), ~~5~~ 4 bytes (SBCS)

Note: APL is not a golfing language.

-1 thanks to Bubbler.

Anonymous tacit prefix function. Takes (array size, current index, movement) as argument.

```
⊃|+/

```

Try it online!

`+/` sum the right argument

`⊃|` division remainder when divided by the first element of the argument

# Answer
> 4 votes
# Jelly, 2 bytes

```
S%

```

A dyadic Link accepting the start index and the rotation on the left and the length on the right which yields the finish index.

**Try it online!**

### How?

```
S% - Link: [start, rotation]; length
S  - sum -> start + rotation
 % - modulo (length)

```

# Answer
> 4 votes
# , 3 bytes

```
|+/

```

Try it online!

We've got APL and Jelly, so here comes J which is between APL and Jelly in the language hierarchy. Turns out the byte count is also in the middle :) And J is not a golfing language either.

Now the byte count is the exact average of Jelly (2B) and APL (4B)!

### How it works

```
|+/  Left: array size, Right: 2-item array of initial index and offset
 +/  index + offset
|    modulo array size

```

# Answer
> 2 votes
# Python, 19 bytes

```
lambda l,p:sum(p)%l

```

An unnamed function accepting `length, (start index, rotation)` which returns the finish index.

**Try it online!**

---

20s:

```
lambda l,i,r:(i+r)%l

```

TIO

```
lambda l,*i:sum(i)%l

```

TIO

```
lambda*a:sum(a)%a[0]

```

TIO

# Answer
> 2 votes
# C (gcc), ~~27~~ 26 bytes

```
r;f(z,i,m){r=(m%z+z+i)%z;}

```

Try it online!

Saved 1 thanks to @att !

# Answer
> 0 votes
# Japt, 5 bytes

```
Nx uU

```

Try it

```
Nx      - sum inputs
   uU   - modulo first input

```

---
Tags: code-golf, array
---


title: Tiling a staircase with staircases

text:
# Question
Title: Tiling a staircase with staircases
## Background

A **staircase polyomino** is a polyomino made of unit squares whose shape resembles a staircase. More formally, a staircase polyomino of size \\$n\\$ is defined as follows:

* A staircase polyomino of size 1 is a single unit square.
* A staircase polyomino of size \\$n\\$ is the same as that of size \\$n-1\\$ with a horizontal bar of length \\$n\\$ attached to the bottom, left-aligned.

Let's call them just **staircases** for brevity.

For example, here are the staircases of size 1 to 4:

```
#

#
##

#
##
###

#
##
###
####

```

## Challenge

Given a positive integer \\$n\\$, calculate the number of ways the staircase of size \\$n\\$ can be tiled with one or more staircases.

Multiple staircases of same size can be used in a tiling, and the staircases can be rotated. So the following are valid tilings for \\$n=4\\$:

```
A
BC
DEF
GHIJ

A
AA
AAA
AAAA

A
AA
BBC
BDCC

```

Standard rules apply. The shortest code in bytes wins.

## Test cases

Generated using this Python 3 reference solution.

```
1 -> 1
2 -> 2
3 -> 8
4 -> 57
5 -> 806
6 -> 20840
7 -> 1038266

```

# Answer
# JavaScript (ES10),  ~~250 ... 228~~  227 bytes

```
n=>(e=g=(a,[x]=a)=>+e?e=0:(x&=-x)?a.map((_,s)=>[b=1<<s,...s?[1,b+=~-b,b]:[]].map((m,d)=>d|x>>s&&g(a.flatMap(S=(v,y)=>(S|=y>s?v:(e|=(v^=M=x*m>>!d*s)&M,m^=1<<[s+~y,y+1,s-y,y][d],v))?v:[])))):n++)([...Array(n)].map(_=>2**n---1))|n

```

Try it online!

### How?

The size-\\$n\\$ staircase is described with an array \\$a\[\\:\]\\$ of \\$n\\$ bit masks, going from the longest to the shortest row.

For \\$n=4\\$, this gives:

```
# # # #  0b1111 = 15
. # # #  0b0111 = 7
. . # #  0b0011 = 3
. . . #  0b0001 = 1  --> a = [ 15, 7, 3, 1 ]

```

At each iteration, we remove all the leading empty rows in \\$a\[\\:\]\\$ and look for the least significant non-zero bit \\$x\\$ in the first non-empty row. Note that \\$x\\$ is not set to the index of this bit, but to the corresponding power of \\$2\\$.

For each \\$s\in\[0\\:..\\:n-1\]\\$ we try to cover the main staircase with another staircase of size \\$s+1\\$ anchored to the non-zero bit, and whose rows are described with the bit mask \\$m\\$. If \\$s=0\\$, we only try the orientation \\$d=0\\$. Otherwise, we try \\$d=0\\$ to \\$d=3\\$.

The table below describes for each value of \\$d\\$:

* the initial value of \\$m\\$
* the index of the bit that must be inverted in \\$m\\$ to generate the next row
* the shift applied to \\$m\\$

The non-zero bit to which the staircase is anchored is marked with an `A`. In all cases, \\$m\\$ is first multiplied by \\$x\\$ before being shifted. All examples are given with \\$x=16\\$ and \\$s=2\\$.

```
             x           d = 0
       . . . . . . . .
y = 0        A           init.  : 2 ** s
y = 1        # #         bit    : s + ~y  (i.e. s - y - 1)
y = 2        # # #       shift  : >> s

             x           d = 1
       . . . . . . . .
y = 0        A           init.  : 1
y = 1      # #           bit    : y + 1
y = 2    # # #           shift  : none

             x           d = 2
       . . . . . . . .
y = 0    # # A           init.  : 2 * (2 ** s) - 1
y = 1      # #           bit    : s - y
y = 2        #           shift  : none

             x           d = 3
       . . . . . . . .
y = 0    # # A           init.  : 2 * (2 ** s) - 1
y = 1    # #             bit    : y
y = 2    #               shift  : none

```

**Note:** Given that the bits to the right of the non-zero bit are all cleared by definition and given that we go from top to bottom, the anchor point of the covering staircase is unambiguously defined for each orientation.
> 13 votes

# Answer
# Charcoal, ~~91~~ ~~88~~ ~~87~~ ~~83~~ ~~81~~ 78 bytes

```
≔⊕Ｎθ⊞υＥθ⁻Ｘ²θＸ²ιＦ⊖θＦθＦＥ²Ｅθ×÷⊖Ｘ²θＸ²⁺ινＸ²⁺κ∧λνＦ⟦λ⮌λ⟧ＦθＦυＦ¬⊙ξ＆π§μ⁻ρν⊞υＥξ｜ρ§μ⁻ςνＩＬυ

```

Try it online! Link is to verbose version of code. This has so many loops that I reached the `v` variable for the first time ever. Explanation:

```
≔⊕Ｎθ

```

Input the size of the staircase and increment it.

```
⊞υＥθ⁻Ｘ²θＸ²ι

```

Create a staircase of that size in such a way that the hole is at the origin. The hole is one size lower, which is the original size we wanted. This becomes our initial tiling (which represents tiling the original staircase with size 1 staircases). The staircase is represented as an array of bit masks.

```
Ｆ⊖θ

```

Consider all staircase sizes greater than 1. (Size 1 staircases are considered by simply assuming that they will be used to fill any hole remaining for each potential tiling.)

```
Ｆθ

```

Consider all horizontal translations.

```
ＦＥ²Ｅθ×÷⊖Ｘ²θＸ²⁺ινＸ²⁺κ∧λν

```

Consider the horizontally translated staircase and its horizontal reflection (actually obtained by shearing).

```
Ｆ⟦λ⮌λ⟧

```

Also consider the vertical reflections of those staircases. (This works because the vertical translations are cyclic.)

```
Ｆθ

```

Also consider all cyclic vertical translations of those staircases. The vertical translation is cyclic so that translations that move the piece too far horizontally will still always overlap the staircase.

```
Ｆυ

```

Loop through all of the tilings collected so far.

```
Ｆ¬⊙ξ＆π§μ⁻ρν

```

If the staircase fits in the hole in this position, then...

```
⊞υＥξ｜ρ§μ⁻ςν

```

... append the result of placing it in the hole to the list of tilings. (Note that Charcoal will find this result in the list again, but of course won't be able to place it twice.)

```
ＩＬυ

```

Output the number of tilings discovered.

Example of avoiding placing a staircase in an impossible position:

```
   \
  \\
 \\\
\\\\/
   //

```

As an example, the double reflection of the size 2 staircase could be moved by 3 horizontally and vertically which would normally cause it to fall outside the original staircase, missing the hole completely. However, the vertical translation is cyclic, so the actual result is as follows:

```
   X/
  \\
 \\\
\\\\/

```

This is therefore detected as an illegal tiling.
> 6 votes

---
Tags: code-golf, combinatorics, tiling, polyomino
---


title: Greatest greatest common divisor

text:
# Question
Title: Greatest greatest common divisor
Find the greatest gcd of the numbers \\$n^m + k\\$ and \\$(n+1)^m + k\\$ for given `m` and `k`.

For example, for `m=3, k=1` we have:

* \\$n = 1\\$: \\$\gcd(1^3 + 1, 2^3 + 1) = 1\\$
* \\$n = 2\\$: \\$\gcd(2^3 + 1, 3^3 + 1) = 1\\$

\\$\vdots\\$

* \\$n = 5\\$: \\$\gcd(5^3 + 1, 6^3 + 1) = 7\\$ (max)

\\$\vdots\\$

* \\$n \to \infty\\$

### Input/Output

Input is L lines through file or stdin, EOF terminated. Each line contains two integers: `m` and `k` separated by a space.

Output is L integers separated by *any pattern* of whitespace characters (tabs, spaces, newlines etc).

### Examples

**Input**

```
2 4
2 7
3 1
4 1
3 2
5 4
10 5

```

**Output**

```
17
29
7
17
109
810001
3282561

```

### Update

I can't find a proof that the solution is bounded for all `n` given some `m` and `k`, so you only have to find the GGCD for \\$n \< 10,000,000\\$.

# Answer
> 6 votes
Update:

GGCD for given `m` and `k` is good defined.

This is table of GGCD tested for n up to 500000.

```
m/k      1       2       3       4       5       6       7       8       9      10
2        5       9      13      17      21      25      29      33      37      41
3        7     109      61     433     169     973     331    1729     547    2701
4       17      33      49      65      81      97     113     129     145    2093
5      341   52501  258751  810001       1  131371       1       1  501311 2846591
6       65     129     193     257   21507     385     449   22059     577     641
7     3683  235747       1       1      71  438299  940507   33461     757  110503
8     4369     513     769   13325    1281  149089  202609    2049  975937  617201
9   359233  232537  202927  470983  123019  708589  241117 5601589  398581   19783
10   62525  514299  183757  807517 1094187 16856405  97477    8193  377897 25919971

```

For `m==2 or 4` it looks quite good :-)

It seems that if **p\_in\_i** is gcd for some **n**, where **p\_i** is a prime, than every combination of products of **p\_i**'s with exponents **\<= n\_i** is also gcd for some **n**. E.g. for m=8,k=2, 3^3 and 19 are gcd of type **p\_in\_i**, also 57, 171 and 513 are gcd's.

Some theory background: If `g = gcd(n) > 1` for some `n`, and `d > 1` and `d divide g` (it can be `d=g`) than `d divide gcd(n±d)`. It is easy to prove. That means:

* If you find some `g = gcd(n) > 1` for some `n`, than `gcd(n±d) > 1`. So, it is enough to jump for found prime number of steps while iterating `n`.
* If prime `p` divide some `gcd()` than there is `n <= p` where `p` divide `gcd(n)`. Prime `p` will 'appear' in `gcd(n)` for some `n <= p`.

These properties can speed up search, but still there is a question is GGCD good defined.

# Answer
> 1 votes
# Ruby - 84 81 80 79 chars

Passes all test cases, not sure if it can handle larger numbers.

```
$<.map{|l|m,k=l.split.map &:to_i;p (1..$$).map{|n|(n**m+k).gcd (n+1)**m+k}.max}

```

### Test

```
D:\tmp>ruby cg_gcd.rb < cg_gcd.in
17
29
7
17
109
3361

```

# Answer
> 1 votes
**Sage, 92**

```
for l in sys.stdin.readlines():m,k=l.split();print max(gcd(n^m+k,(n+1)^m+k)for n in[1..1e7])

```

# Answer
> 1 votes
# Jelly, 9 bytes

```
*@Ɱȷ7+gƝṀ

```

Try it online!

This times out on TIO no matter the input due to the `Ɱȷ7` which iterates over the range \\$1, 2, ..., 10^7\\$. By reducing the `7` to a smaller value, we can get TIO to actually output some results (obviously it gets it wrong for inputs where \\$n \> 10^5\\$): Try it online!

Not exactly spec-conforming, but given the age I didn't see much issue with that. Takes input in the form of command line arguments. \\$m\\$ first, then \\$k\\$

## How it works

```
*@Ɱȷ7+gƝṀ - Main link. Takes m as a left argument and k on the right
   ȷ7     - 10000000
  Ɱ       - Over each n between 1 and 10000000:
*@        -   Calculate n^m
     +    -   Add k
       Ɲ  - Over each neighbouring pair in the list (i.e. n^m+k and (n+1)^m+k):
      g   -   Calculate their GCD
        Ṁ - Output the maximum

```

---
Tags: code-golf, number-theory
---


# Question
Title: Count from 1 to n in Negabinary and Negaquaternary
Instead of normal binary, you must count from 1 to an input in **negabinary concatenated to negaquaternary**.

Here's an example, put in the form of an array:

```
[11, 1102, 1113, 100130, 101131, 11010132, 11011133, 11000120, 11001121, 11110122, 11111123, 11100110, 11101111, 10010112, 10011113, 10000100, 10001101, 10110102, 10111103, 10100230, 10101231, 1101010232, 1101011233, 1101000220, 1101001221, 1101110222, 1101111223, 1101100210, 1101101211, 1100010212, 1100011213, 1100000200, 1100001201, 1100110202, 1100111203, 1100100330, 1100101331, 1111010332, 1111011333, 1111000320, 1111001321, 1111110322, 1111111323, 1111100310, 1111101311, 1110010312, 1110011313, 1110000300, 1110001301, 1110110302, 1110111303, 111010013030, 111010113031, 100101013032, 100101113033, 100100013020, 100100113021, 100111013022, 100111113023, 100110013010, 100110113011, 100001013012, 100001113013, 100000013000, 100000113001, 100011013002, 100011113003, 100010013130, 100010113131, 101101013132, 101101113133, 101100013120, 101100113121, 101111013122, 101111113123, 101110013110, 101110113111, 101001013112, 101001113113, 101000013100, 101000113101, 101011013102, 101011113103, 101010013230, 101010113231, 11010101013232, 11010101113233, 11010100013220, 11010100113221, 11010111013222, 11010111113223, 11010110013210, 11010110113211, 11010001013212, 11010001113213, 11010000013200, 11010000113201, 11010011013202, 11010011113203, 11010010013330]
```

Your program must produce those numbers in any of these forms:

* spaced apart
* in an array
* on new lines

### How do I get those numbers?

Integer `n` will be used as an example of input.

```
for i := 1 to n
    print "i in base -2" + "i in base -4"

```

### Rules:

* You can submit a function or a whole program
* You can go from 0 or 1 to the input
* Builtins are allowed

# Answer
> 3 votes
# , 18 bytes

```
j){n.2_bo4_bo' o}d
```

Just my own take on this. Prints numbers with a space between them.

Try it online

Explanaiton:

```
j)                 Increment input by 1
  {             }d Do this (input+1) times
   n.2_bo          Convert n to base -2 and output
         4_bo      Convert n to base -4 and output
             ' o   Output a space

```

# Answer
> 5 votes
## Python - 83 bytes

```
f=lambda i,k:i and f(-i/k,k)+`-i%k`or''
i=0;exec"i-=1;print f(i,2)+f(i,4);"*input()

```

`f` is a function that converts (the negation of) an integer *i* to a negative base *2 ≤ k ≤ 10*. Input is taken from stdin.

---

**Sample Usage**

```
$ echo 30 | python nega2+4.py
11
1102
1113
100130
101131
11010132
11011133
11000120
11001121
11110122
11111123
11100110
11101111
10010112
10011113
10000100
10001101
10110102
10111103
10100230
10101231
1101010232
1101011233
1101000220
1101001221
1101110222
1101111223
1101100210
1101101211
1100010212

```

# Answer
> 4 votes
# Julia, ~~124~~ ~~81~~ 73 bytes

```
n->(a=2863311530;b=3435973836;[base(2,(i+a)$a)*base(4,(i+b)$b)for i=1:n])

```

This creates an unnamed function that accepts an integer and returns an array. Each element of the array is a successive number between 1 and *n* in negabinary concatenated to itself in negaquaternary.

The negabinary representation of an integer can be computed using Schroppel's shortcut:

```
base(2, (i + 2863311530) $ 2863311530)

```

For an integer *i*, this is *i* \+ 2863311530, XOR 2863311530, encoded in base 2. The negaquaternary shortcut is similar:

```
base(4, (i + 3435973836) $ 3435973836)

```

# Answer
> 2 votes
# Pyth - 31 30 29 27 bytes

Uses Forumla by D. Librik (Szudzik) (look at negabinary and quaternary sections). Can probably be golfed a bit.

```
VQjksjVmx+NKi*8d16K"AC",2 4

```

Prints from zero on separate lines.

```
VQ                   For i in 0-Q
 jk                  Join by empty string
  s                  Sum of two arrays
   jV                Vectorized base conversion
    m       "AC"     Map of A and C
     x               Bitwise xor
      +NK            Sum of loop var and constant inline assigned
       i  16         To base 10 from 16
        *8           String repetition times 8
         d           Map var
      K              Xnor of constant
   ,2 4              Bases 2 and 4

```

Try it here online.

# Answer
> 2 votes
# CJam, ~~34~~ ~~33~~ 32 bytes

I think this can be golfed further. Counts from 0.

```
li),{_[CA]{:Ba8*Gb_@+^B8-b\}/N}/

```

Try it online.

# Answer
> 1 votes
# Jelly, 10 bytes

```
bF¥€Ø½ḤN¤Ḍ

```

Try it online!

## How it works

```
bF¥€Ø½ḤN¤Ḍ - Main link. Takes an integer as left argument
    Ø½ḤN¤  - Yield the list [-2, -4]:
        ¤  -   Group the previous commands into a constant:
    Ø½     -     Start with [1, 2] (builtin constant)
      Ḥ    -     Double     [2, 4]
       N   -     Negate     [-2, -4]
  ¥€       - Generate the range 1...n and do the following to each:
b          -   Convert to bases -2 and -4
           -   For example, 5b[-2, -4] => [[1, 0, 1], [1, 3, 1]]
 F         -   Flatten the lists          [1, 0, 1, 1, 3, 1]
         Ḍ -   Convert to a number        101131

```

# Answer
> 0 votes
# Japt, 12 bytes

Output is an array of digit arrays.

```
õìJÑ)ícUõì4n

```

Try it

---
Tags: code-golf, counting, base-conversion
---


title: 20 cards with no Set

text:
# Question
Title: 20 cards with no Set
## Background

**Set** is a card game. The deck consists of 81 unique cards that vary in four features: number of shapes (one, two, or three), shape (diamond, squiggle, oval), shading (solid, striped, or open), and color (red, green, or purple).

For convenience, let's write a card as a 4-tuple of numbers from 1 to 3, e.g.

* `1111` = one red solid diamond
* `1122` = one red striped squiggle
* `1223` = one green striped oval
* `2312` = two purple solid squiggle

Given several cards (usually 12), the objective of the game is to find a "set" of three cards such that

* They all have the same number or have three different numbers.
* They all have the same shape or have three different shapes.
* They all have the same shading or have three different shadings.
* They all have the same color or have three different colors.

i.e. the cards are either **all the same or all different in each of the four features**.

Here are some examples of sets:

```
1111, 1112, 1113
1111, 2222, 3333
2312, 3321, 1333

```

Here are some examples of non-sets:

```
1111, 1122, 1123
2131, 3221, 1213

```

A **cap set** is a collection of cards that doesn't contain any Set. It was proven in 1971 that the maximum number of cards without a Set is 20. Interestingly, finding the largest cap set for the generalized game of Set is still an open problem in mathematics.

The Wikipedia page shows an example of 20-cap set, and here is the 20 cards in the number notation:

```
1111, 1113, 1131, 1133,
1312, 1332, 1321, 1323,
3311, 3313, 3331, 3333,
3112, 3132, 3121, 3123,
1222, 2122, 2322, 3222

```

There are 682344 20-cap sets in total, but under affine transformations on 4-dimensional finite space, they all reduce to essentially one cap set.

## Task

Output any of the 20-cap sets in the game of Set.

## Input and output

Your program/function is not allowed to take input.

The output is a collection (list, set, ...) of 20 cards which is a cap set. Each card should be represented as a 4-tuple (or equivalent ordered collection) whose elements are one of three distinct values (not necessarily 1, 2, 3). Flexible output applies in the following ways:

* Nested or flattened list
* Ordering of cards doesn't matter
* You may choose to output the same set or different set across runs
* For string/text output, it's fine as long as we can clearly identify the structure (20 chunks of four items) of the output

Verification script example in Python using the example shown above.

## Scoring and winning criterion

Standard rules apply. The shortest valid code in bytes wins.

# Answer
# Haskell, 62 bytes

```
tail[t|t@[a,b,c,d]<-mapM(:[1,2])[0,0,0,0],mod(a*a+b*b+c*d)3<1]

```

Try it online!

Defines a cap-set as all \\$(a,b,c,d)\\$ from \\$\\{0,1,2\\}^4\\$ where $$a^2+b^2+cd=0\bmod3,$$ except not \\$(0,0,0,0)\\$.

I found this formula by looking at Wikipedia's example and coming up with progressively simpler formulas linking the allowed inner coordinates \\$(a,b)\\$ to the outer coordinates \\$(c,d)\\$.

---

# Haskell, 46 bytes

```
[t|t<-mapM(:"12")"0000",sum[1|'0'<-t!!0:t]==2]

```

Try it online!

This uses a modified condition giving a different but equivalent cap set:

$$a^2+b^2+c^2 - d^2=0\bmod3,$$ still without \\$(0,0,0,0)\\$.

This is equivalent to \\$a^2+b^2+c^2 + d^2 + d^2 =0\bmod3,\\$, so we can duplicate an element and check that the give-element list of squares adds to zero modulo 3. Since squares modulo 3 are 0 or 1, this is further equivalent to this condition:

> There are exactly \\$2\\$ zeroes among \\$\[a,b,c,d,d\]\\$.

This automatically excludes the all-zero point. Of course, duplicating $d$ was arbitrary -- choosing another element gives a different but equivalent cap-set.
> 25 votes

# Answer
# 05AB1E, ~~16~~ ~~13~~ ~~11~~ 9 bytes

```
2Ý4ãʒĆ0¢<

```

Port of the found formula of *@xnor*, as mentioned in his comment as well as his Haskell answer, so make sure to upvote him!
-2 bytes by using *@xnor*'s updated formula (thanks for letting me know).
-2 bytes thanks to *@xnor* again by simply counting whether there are exactly 2 zeroes in \\$\[a,b,c,d,a\]\\$.

Also outputs a list of lists with values in the range \\$\[0,3\]\\$.

Try it online.

**Explanation:**

Will leave quartets \\$\[a,b,c,d\]\\$ for which there are exactly 2 zeroes in the list \\$\[a,b,c,d,a\]\\$.

```
2Ý         # Push the list [0,1,2]
  4ã       # Create all possible quartets using the values in this list
           # by taking the cartesian power of 4
    ʒ      # Filter the remaining quartets by:
     Ć     #  Enclose the quartet; appending its own head: [a,b,c,d] → [a,b,c,d,a]
      0¢   #  Count the amount of 0s in this list
        <  #  And decrease it by one
           #  (Since only 1 is truthy in 05AB1E, the filter with count(0)-1 will only
           #   leave quartets where the [a,b,c,d,a].count(0) is exactly 2)
           # (after which the filtered list is output implicitly as result)

```
> 8 votes

# Answer
# JavaScript (ES6),  ~~73~~  67 bytes

```
_=>[...'11138272726454626454'].map(i=>3333-(t-=i).toString(3),t=80)

```

Try it online!

Outputs the following set, as an array of integers:

```
1112, 1113, 1121, 1131, 1223, 1232, 1323, 1332, 2123, 2132,
2222, 2233, 2322, 2333, 3123, 3132, 3222, 3233, 3322, 3333

```

Test it online!
> 7 votes

# Answer
# Perl 6, ~~46~~ 36 bytes

```
{grep *[0,^*].Bag{0}==2,[X] ^3 xx 4}

```

Try it online!

Uses xnor's *updated* formula.

### Explanation:

```
{                                  }  # Anonymous code block
 grep                                 # Filter from
                       ,[X]             # The cross product of
                            ^3 xx 4     # 0,1,2 four times
      *[0,^*]                         # Duplicating the first element
             .Bag{0}                  # Where the number of zeroes
                    ==2               # Is equal to 2

```
> 5 votes

# Answer
# APL (Dyalog Unicode), ~~21~~ 19 bytes

*-2 bytes thanks to Bubbler*

```
((3=1⊥5⍴×)¨⊆⊢),⍳4/3

```

Try it online!

This uses xnor's formula, finding all cards from the permutation that when the first attribute is duplicated, has exactly 2 zeroes (this code being 0-indexed). The output is slightly weird, since some cards are grouped together, but you can still make out the individual cards.

### Explanation

```
              ,⍳4/3     ⍝ Generate all length 4 permutations of 0,1,2
 (       )¨             ⍝ For each permutation, e.g 0,1,2,1
        ×               ⍝ Get the sign,         e.g 0,1,1,1
      5⍴                ⍝ Reshape to size 5     e.g 0,1,1,1,0
    1⊥                  ⍝ Base 1 (or sum)       e.g 3
  3=                    ⍝ Is equal to 3         e.g 1
           ⊆⊢           ⍝ And partition the ones that return true

```
> 5 votes

# Answer
# Ruby, ~~78..52~~ 49 bytes

```
"U ".bytes{|r|p ($.+=r).to_s 4}

```

Try it online!

### How

The sequence can be DPCM-encoded.

If we consider a card as a single base-4 integer (1111 through 3333), we can take any sequence, sort it, and use a single ASCII character to encode the difference between successive elements. The first character represents the first value of the sequence. All values are relatively small, and the decoding is still simple enough to be golfed.

Thanks Value Ink for -3 bytes ("to print the unprintable")

In theory, with a different encoding, every value can be encoded as a single byte, and this would bring the byte count down to 43, but with UTF-8 it's impossible (or at least, I can't figure it out).
> 4 votes

# Answer
# Jelly,  ~~13~~  11 bytes

-2 using more of xnor's ideas

```
3ṗ4ṁ5ỊS⁼ʋƇ2

```

A niladic Link which yields a list of lists of integers.

**Try it online!**

### How?

Cards being `[a, b, c, d]` where \\$a,b,c,d \in \[1,3\]\\$ this method picks cards for which there are exactly two `1`s in `[a, b, c, d, a]`.

```
3ṗ4ṁ5ỊS⁼ʋƇ2 - Link: no arguments
3           - literal three
  4         - literal four
 ṗ          - (implicit range(x)) Cartesian power -> [[1,1,1,1],[1,1,1,2],...,[3,3,3,3]]
          2 - set the right argument to two
         Ƈ  - filter keep if:
        ʋ   -   last four links as a dyad:
   ṁ5       -     mould like 5 ([a,b,c,d] -> [a,b,c,d,a])
     Ị      -     insignificant? (abs(x)<=1) (vectorises)
      S     -     sum
       ⁼    -     equals (2)?

```

---

Previous

```
3ṗ4Ṗ2œ?ḋƊ3ḍƊƇ

```

A niladic Link which yields a list of lists of integers.

**Try it online!**

### How?

A method which works in a similar vein as xnor's.
With cards being `[a, b, c, d]` where \\$a,b,c,d \in \[1,3\]\\$ this method picks cards for which \\$3 \mid (a^2+b^2+2cd)\\$ (except `[3,3,3,3]`)

```
3ṗ4Ṗ2œ?ḋƊ3ḍƊƇ - Link: no arguments
3             - literal three
  4           - literal four
 ṗ            - (implicit range(x)) Cartesian power -> [[1,1,1,1],[1,1,1,2],...,[3,3,3,3]]
   Ṗ          - pop off the rightmost (remove [3,3,3,3])
            Ƈ - filter keep those for which:
           Ɗ  -   last three links as a monad:- i.e. f([a,b,c,d])
        Ɗ     -     last three links as a monad - i.e. g([a,b,c,d]):
    2         -       literal two                 2
     œ?       -       nth permutation             [a,b,d,c]
       ḋ      -       dot product                 a*a+b*b+c*d+d*c
         3    -     literal three               3
          ḍ   -     divides?                    (a*a+b*b+c*d+d*c)%3 == 0?

```
> 2 votes

# Answer
# Charcoal, 24 bytes

```
ＵＢ0Ｅ²⁰⮌⍘Σ…”)″&:igＫ⁶Mψ”ι³

```

Try it online! Link is to verbose version of code. Outputs the given set, but with digits decremented and sorted in order of reverse of string. Explanation:

```
ＵＢ0

```

Pad all lines to the same length using `0`.

```
Ｅ²⁰

```

Loop `i` from 0 to 19 and implicitly print each result on its own line.

```
⮌⍘Σ…”)″&:igＫ⁶Mψ”ι³

```

Convert the digital sum of the `i`th prefix of the compressed string `8343834422244383438` to base 3 and print it backwards.
> 2 votes

# Answer
# Python 2, 85 bytes

```
print eval('[[a,b,c,d]'+'for %s in 0,1,2'*4%tuple('abcd')+'if(a*a+b*b+c*d)%3<1]')[1:]

```

A full program which performs xnor's algorithm.

**Try it online!**
> 2 votes

# Answer
# Python 2, 62 bytes

```
for c in"P}nF-Z>a9*)V=.Q":n=ord(c);print n/50,n%3,n%4,n%5

```

Try it online!

Using ideas from Bubbler and Jo King, we can cut a few bytes from the below. The decompression method `n/50,n%3,n%4,n%5` turns an ASCII value into a 4-tuple. While not every set can be obtained this way using `n` from 0 to 127, there's enough wiggle room in the choice of cap-set to find one within the obtainable subset. We also avoid problematic characters that need escaping such as `\0` or `\n`, though unprintables can't be avoided.

---

**Python 2, 65 bytes**

```
for c in'RSTW_ahjq"(,15;=CGLP':print[ord(c)/B%3for B in 27,9,3,1]

```

Try it online!

String compression looks like the way to go for Python. We compress each of the 20 elements as a value from 0 to 80, which we represent as a character. Since we only need the values to be correct modulo 81, we can keep the string within the printable ASCII range. Python 3 could save a few bytes using a bytestring.

An alternative compression method would be 81 bits marking which of the 81 cards are present. Even though the 81 bits needed for this are less than the \\$20 \log\_2(81)\approx 127\\$ bits for the method used, the latter wins out easily for how concisely the string can be written and decoded.

For comparison, here's a solution using the formula I found.

**79 bytes**

```
n=81
while n:
 t=a,b,c,d=n/27,n/9%3,n/3%3,n%3;n-=1
 if(a*a+b*b+c*d)%3<1:print t

```

Try it online!
> 2 votes

# Answer
# Brachylog, 32 bytes

Just an inefficient Brachylog answer passing by, both in speed and bytes. But it works in the generalized case and will give every possible set if you let it run several years!

```
l₂₀{l₄ℕᵐ<ᵛ³}ᵐ{cᵐ≠&}¬{⊇l₃\{=|≠}ᵐ}&≜

```

Try it online! … or don't; this will just give you a 5 cap set, the maximum for TIO's time limit. The version uses up/down arrows for ease of use. First number is size of cap set, second is number of properties per card, and third is variations of each property. The 6 cap set I found locally: `[[0, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [0, 1, 1, 1], [1, 0, 0, 0]]`.

### How it works

```
l₂₀{l₄ℕᵐ<ᵛ³}ᵐcᵐ≠&¬{⊇l₃\{=|≠}ᵐ}&≜ (the implicit input we are looking for)
l₂₀                              is a list of 20 cards,
   {       }ᵐ                    where each card
    l₄                             has 4 elements,
      ℕᵐ                           numbers >= 0 – to be precise
        <ᵛ³                        that are also lower than 3
                                   (so [0,0,0,0] up to [2,2,2,2])
             cᵐ                  if each card is concatenated to a string,
               ≠                   they would be different. (sadly ≠
                                   doesn't work on lists.)
                 &¬{          }  the following doesn't hold for the input:
                    ⊇l₃            take any list of 3 cards,
                       \           transpose it
                                   ([[0,1,2],[3,2,1],[0,0,0],[2,2,2]])
                        {   }ᵐ   each of the row's elements are …
                         =|≠       either equal or different to each other
                              &≜ actually get some numbers for the list

```
> 2 votes

# Answer
# Python 3, ~~108~~ ~~104~~ 100 bytes

Saved 4 bytes thanks to @JonathanAllan!
Saved 4 bytes thanks to @xnor!

Blatant rip of @xnor's algorithm:

```
lambda:[(a,b,c,d)for a,b,c,d in product(*[(0,1,2)]*4)if(a*a+b*b+c*d)%3<1][1:]
from itertools import*

```

Try it online!
> 1 votes

# Answer
# Scala, 68 bytes

```
BigInt("3aglhdjjb0zmp3uvkpxvwio58",36).toString(3).grouped(4).toList

```

Try it online!

Just storing the 20-cap set as a 80-digit base-3 number (using 0, 1, 2 for notation - since it's stated in the question that it's not necessary to use exactly 1, 2, 3), constructing it from base-36 to save space, and splitting the string to 4-character slices, finally getting a list of 20 cards (represented as strings like "1111", "0222" etc.). A couple more bytes probably can be golfed, using a smaller number.
> 0 votes

---
Tags: code-golf, card-games
---


title: Approximate when you are going to die

text:
# Question
Title: Approximate when you are going to die
A mortality table or life table is an actuarial tool that gives the probability that a person aged \\$A\\$ years will die in the next year, and is used to help calculate the premiums for life insurance, among other things. One of the first people to compile a life table was Edmond Halley, of cometary fame. These probabilities also allow you to estimate the life expectancy for a given age, which is the goal of this challenge.

# Input

* An integer from 0 to 119, inclusive.
* An indicator for Sex M/F.

# Output

```
Age     M           F
0       75.97       80.96
1       75.45       80.39
2       74.48       79.42
3       73.50       78.43
4       72.52       77.45
5       71.53       76.46
6       70.54       75.47
7       69.55       74.47
8       68.56       73.48
9       67.57       72.49
10      66.57       71.50
11      65.58       70.50
12      64.59       69.51
13      63.60       68.52
14      62.61       67.53
15      61.63       66.54
16      60.66       65.55
17      59.70       64.57
18      58.74       63.59
19      57.79       62.61
20      56.85       61.63
21      55.91       60.66
22      54.98       59.69
23      54.06       58.72
24      53.14       57.75
25      52.22       56.78
26      51.31       55.82
27      50.39       54.85
28      49.48       53.89
29      48.56       52.93
30      47.65       51.97
31      46.74       51.01
32      45.83       50.06
33      44.92       49.10
34      44.01       48.15
35      43.10       47.20
36      42.19       46.25
37      41.28       45.30
38      40.37       44.36
39      39.47       43.41
40      38.56       42.47
41      37.65       41.53
42      36.75       40.59
43      35.85       39.66
44      34.95       38.73
45      34.06       37.80
46      33.17       36.88
47      32.28       35.96
48      31.41       35.04
49      30.54       34.13
50      29.67       33.23
51      28.82       32.33
52      27.98       31.44
53      27.14       30.55
54      26.32       29.68
55      25.50       28.81
56      24.70       27.94
57      23.90       27.09
58      23.12       26.24
59      22.34       25.39
60      21.58       24.56
61      20.83       23.72
62      20.08       22.90
63      19.35       22.07
64      18.62       21.26
65      17.89       20.45
66      17.18       19.65
67      16.47       18.86
68      15.77       18.07
69      15.07       17.30
70      14.39       16.54
71      13.71       15.79
72      13.05       15.05
73      12.40       14.32
74      11.76       13.61
75      11.14       12.92
76      10.53       12.23
77      9.94        11.57
78      9.37        10.92
79      8.82        10.29
80      8.28        9.68
81      7.76        9.09
82      7.26        8.52
83      6.79        7.98
84      6.33        7.45
85      5.89        6.95
86      5.48        6.47
87      5.08        6.01
88      4.71        5.57
89      4.37        5.16
90      4.05        4.78
91      3.75        4.43
92      3.48        4.11
93      3.23        3.81
94      3.01        3.55
95      2.81        3.31
96      2.64        3.09
97      2.49        2.90
98      2.36        2.73
99      2.24        2.58
100     2.12        2.42
101     2.01        2.28
102     1.90        2.14
103     1.80        2.01
104     1.70        1.88
105     1.60        1.76
106     1.51        1.65
107     1.42        1.54
108     1.34        1.44
109     1.26        1.34
110     1.18        1.24
111     1.10        1.15
112     1.03        1.06
113     0.96        0.98
114     0.90        0.91
115     0.84        0.84
116     0.78        0.78
117     0.72        0.72
118     0.66        0.66
119     0.61        0.61

```

For convenience, here they are in wide form (ages 0-119 in order):

```
M: [75.97, 75.45, 74.48, 73.5, 72.52, 71.53, 70.54, 69.55, 68.56, 67.57, 66.57, 65.58, 64.59, 63.6, 62.61, 61.63, 60.66, 59.7, 58.74, 57.79, 56.85, 55.91, 54.98, 54.06, 53.14, 52.22, 51.31, 50.39, 49.48, 48.56, 47.65, 46.74, 45.83, 44.92, 44.01, 43.1, 42.19, 41.28, 40.37, 39.47, 38.56, 37.65, 36.75, 35.85, 34.95, 34.06, 33.17, 32.28, 31.41, 30.54, 29.67, 28.82, 27.98, 27.14, 26.32, 25.5, 24.7, 23.9, 23.12, 22.34, 21.58, 20.83, 20.08, 19.35, 18.62, 17.89, 17.18, 16.47, 15.77, 15.07, 14.39, 13.71, 13.05, 12.4, 11.76, 11.14, 10.53, 9.94, 9.37, 8.82, 8.28, 7.76, 7.26, 6.79, 6.33, 5.89, 5.48, 5.08, 4.71, 4.37, 4.05, 3.75, 3.48, 3.23, 3.01, 2.81, 2.64, 2.49, 2.36, 2.24, 2.12, 2.01, 1.9, 1.8, 1.7, 1.6, 1.51, 1.42, 1.34, 1.26, 1.18, 1.1, 1.03, 0.96, 0.9, 0.84, 0.78, 0.72, 0.66, 0.61]
F: [80.96, 80.39, 79.42, 78.43, 77.45, 76.46, 75.47, 74.47, 73.48, 72.49, 71.5, 70.5, 69.51, 68.52, 67.53, 66.54, 65.55, 64.57, 63.59, 62.61, 61.63, 60.66, 59.69, 58.72, 57.75, 56.78, 55.82, 54.85, 53.89, 52.93, 51.97, 51.01, 50.06, 49.1, 48.15, 47.2, 46.25, 45.3, 44.36, 43.41, 42.47, 41.53, 40.59, 39.66, 38.73, 37.8, 36.88, 35.96, 35.04, 34.13, 33.23, 32.33, 31.44, 30.55, 29.68, 28.81, 27.94, 27.09, 26.24, 25.39, 24.56, 23.72, 22.9, 22.07, 21.26, 20.45, 19.65, 18.86, 18.07, 17.3, 16.54, 15.79, 15.05, 14.32, 13.61, 12.92, 12.23, 11.57, 10.92, 10.29, 9.68, 9.09, 8.52, 7.98, 7.45, 6.95, 6.47, 6.01, 5.57, 5.16, 4.78, 4.43, 4.11, 3.81, 3.55, 3.31, 3.09, 2.9, 2.73, 2.58, 2.42, 2.28, 2.14, 2.01, 1.88, 1.76, 1.65, 1.54, 1.44, 1.34, 1.24, 1.15, 1.06, 0.98, 0.91, 0.84, 0.78, 0.72, 0.66, 0.61]

```

# Scoring Rules

For this challenge, **the submission with the lowest score wins**. Your score will be equal to \\$(1+L)\times(1 + M)\\$, where \\$L\\$ is the length of your code in bytes and \\$M\\$ is the mean-squared error of your estimates, rounded to two decimal places. This is a scoring program for \\$M\\$.

# Other rules

* Standard loopholes are forbidden.
* Input is pretty flexible. You can specify any two distinct values for M/F: `'M'/'F'`,`0/1`. If you really wanted, you could even take a single integer, with the sign representing M/F, but note that `0` is an input for both. Or the real and imaginary parts of a complex number.
    + You don't have to take any input if you don't want, which should allow you to post answers that just always return 4 or whatever.
* In case there was any confusion, the output *cannot* be random.
* Please include a means of verifying your score.
* Builtins that have this exact mortality table are not banned, but do please implement your own solution as well.
* Explanations are encouraged.

# Additional Bonuses:

Since R is the language of the month for September 2020, I will be awarding a 500 rep bounty to the R answer with the best score at the end of the month.

# Answer
# JavaScript (ES6), Score:  ~~59.51~~  59.10

**L = 52 bytes, M ≈ 0.1150638**

Expects `(n)(m)`, where **m** is **1** for Male or **0** for Female.

```
n=>m=>81-5*m-(.9+m/51+(70-27*m-(.92-m/7)*n)/2e4*n)*n

```

Try it online!

or Get the raw data in the format expected by the scoring program.

### Method

This is based on two cubic regressions, with a trade-off between code size and accuracy.

For women, this computes:

$$f\_0(x)=81-\frac{9}{10}x-\frac{7}{2000}x^2+\frac{23}{500000}x^3$$

And for men:

$$f\_1(x)=76-\frac{469}{510}x-\frac{43}{20000}x^2+\frac{17}{437500}x^3$$

### How accurate is it?

Below is a graph of the errors produced by the function according to the age and the sex.
> 12 votes

# Answer
# , score=~~67.47~~ 47.92

30 bytes, MSE = 0.54587

-1 byte (and -1.47 in score) thanks to Dominic van Essen.

```
pnorm(scan(),31,41,F)*scan()-2

```

Try it online!

The input format is: age as an integer, then a newline, then sex, then a newline. Sex is encoded as 98 for men and 106 for women.

Approximates the actuarial tables by the survival function of a normal distribution (the survival function is 1 - the cumulative distributions function). I tried a few families of distribution, and the normal minimized the MSE.

Let \\$\phi(x;\mu,\sigma)\\$ be the density of a \\$\mathcal N(\mu,\sigma^2)\\$ distribution. The approximation used is

\\$f(x)=a+m\int\_x^\infty\phi(t;\mu,\sigma)\\,dt\\$

I tried using different parameter values for men and women, but the best score is obtained by using the same values of \\$a\\$, \\$\mu\\$ and \\$\sigma\\$, and picking only different values for \\$m\\$. Since \\$m=98\\$ for men and \\$m=106\\$ for women are the optimal values, I use those to encode the sex directly.

(Actually, the optimal values would be \\$m=98.25528\\$ for men and \\$m=106.34315\\$ for women, but using such values to define the sexes really feels like cheating. It would lead to a score of 47.49, a slight improvement.)

Plot of the approximation for men:

Plot of the approximation for women:
> 12 votes

# Answer
# Wolfram Language (Mathematica), Score 151.8,

# 32 bytes, 3.6 MSE

```
#-Cos[x(Pi-.02)/238]~Sum~{x,#2}&

```

Try it online!

I noticed that the differences of the values were similar to `Cos(x) [0,pi/2]`
So, accumulated Cos(x) works pretty good on men...

***MALE***
**MSE 0,90**

***FEMALE***
**MSE 6,29**
(*I guess Cos(x) understands men better...*)

Special thanks to @att for golfing my code down to 33 bytes
> 7 votes

# Answer
# Ruby, score ~~56.12...43.94~~ 43.92

\\$L=35\\$, \\$M\approx0.220060\\$

```
->x,f{f.*1.87e6-(21676+(66-x)*x)*x}

```

Try it online!

Input is an age \\$x\\$ and a float \\$f\\$, which is `4.027e-5` for male and `4.362e-5` for female. (See below for an alternative version that takes \\$f\\$ as an integer instead.) The approach is to fit a cubic polynomial to the life expectancy averaged across both sexes, then scale this polynomial by a *sex factor* to recover sex-specific approximations. The polynomial selected for the average life expectancy is $$ \frac{x^3-66x^2-21676x+1870000}{23840} $$ and the sex factor is $$ \begin{cases}0.96,\\;\text{male}\\1.04,\\;\text{female}.\end{cases} $$ In other words, the life expectancy of a male is approximately \\$0.96\\$ times that of an average human (male or female). Similarly, the life expectancy of a female is approximately \\$1.04\\$ times that of an average human.

The plot below shows the squared error as a function of age for each sex. The dashed grey line represents the mean squared error for both sexes.

One point of interest in the code is the explicit call to the `*` method of the float `f`. Everything to the right of `f.*` is interpreted as the method argument, so the polynomial doesn't need to be enclosed in parentheses.

---

# Ruby, score 50.06

\\$L=40\\$, \\$M\approx0.220981\\$

```
->x,f{f/9e3*(56541-(656+(2-x/33r)*x)*x)}

```

Try it online!

Despite being within the rules, taking \\$f\\$ as a float (as above) feels more than a little 'cheaty'. This version uses the same general approach, but here \\$f\\$ is an integer: \\$12\\$ for male and \\$13\\$ for female. The polynomial used for the average life expectancy is $$ \frac{x^3/33-2x^2-656x+56541}{720}. $$
> 7 votes

# Answer
# , score 53.76 52.78

`L = 46`, `M = 0.122983`

Takes M/F as 1/0 on the right side and age on the left side. A simple third degree polynomial approximation. The J polynomials read from left to right, so `81 - 0.9x - 347e-5x² + 455e-7x³` for the 1 case. The 0 case just modifies the numbers a little bit to `76 - 0.92x - 207e-5x² + 385e-7x³`. `p.` evaluates the polynomial at `x`, in this case the age.

```
p.~81 _0.9 _347e_5 455e_7-5 0.02 _14e_4 7e_6&*

```

Try it online!
> 5 votes

# Answer
# Python 3, score 94.40, 58 bytes, 0.60 MSE

Just simple linear approximations. `True` for *female* and `False` for *male*.

```
lambda a,g:[75+5*g-(.89+g/30)*a,12-a/11][a>81]+(70<a<90)*2

```

Try it online!

Visual representation of the approximation:
> 3 votes

# Answer
# , score 46.00036

*Pushing the limits of 'any two distinct values' as input more than somewhat...*

45 bytes, mean-squared-error 7.9e-6

```
function(a,s)s%/%gmp::as.bigz(1e4)^a%%1e4/100

```

Try it online!

Input is an integer `a` as age, and one of two 'big integer' values `s` to specify M/F sex.
Output is a 'big rational' number.

As (presumably) encouraged by the generously-flexible input rules, the sex-specifying values are integral for the calculation (although in this case probably more so than intended...).
Each of M,F big integers are constructed as the 1...120th power of 1e4 multiplied by 100x the life expectancy at each age: essentially, a base-10000-encoding. The `life_expectancy` function simply decodes the `a`th base-10000 digit and divides by 100.

Even though the function uses the arbitrary-precision `gmp` library for calculations, a small number of the decoded values still contain inaccuracies at the 2nd decimal place, for reasons that I don't understand.
Nevertheless, the mean-squared-error is (as expected) sufficiently close to zero that this doesn't matter, since we need to add 1 to it anyway to get the score.
> 3 votes

# Answer
# , score 75.74445

61 bytes, mean-squared-error 0.222

```
function(a,s)s*predict(loess(c(82,58,35,14,3,1)~c(0:5*24)),a)

```

Try it online!

Uses loess smoothing to interpolate between hard-coded data points.

The M and F curves are remarkably similar to each other after scaling (by 0.92x) - see the black & grey points on the graph - so the hard-coded points are taken from the mean of the two (scaled) curves, and then rounded to nice, short values. The red line on the graph shows the interpolated values.

Unfortunately (for me), the scoring system of adding 1 to the mean-square-error strongly rewards reasonably-close fits, but doesn't give very much more reward for a *very*-close-fit, so the extra code-length here means that the overall score is still worse than Robin Ryder's looser fit to a normal distribution.
> 2 votes

# Answer
# Wolfram Language (Mathematica), score 34.16

## 27 bytes, mean square error 0.21676 (rounded to 0.22)

```
#3(#2-#+Sqrt[(#2-#)^2+#4])&

```

Try it online!

An unnamed function (which we will call `f` for the purposes of discussion) which takes two arguments (in this order), the age (an integer from 0 to 119) and the indicators for female or male in this form:

* indicator for "female": `Sequence[83.506,0.4794,222.8]`
* indicator for "male": `Sequence[80.596,0.4636,248.5]`

In Mathematica, `f[a,Sequence[b,c,d]]` is the same as `f[a,b,c,d]`; so `Sequence[b,c,d]` is almost exactly an ordered triple, except it's better for plugging into functions.

The above code implements the mathematical function

\\$ f(a,b,c,d) = c\big( b-a + \sqrt{(b-a)^2+d} \big), \\$

where \\$a\\$ is the age and \\$b,c,d\\$ are numerical parameters used to optimize the fit with the data.

This specific form was motivated by my perception that the graphs of the data for each sex looked like a hyperbola with a slant asymptote to the left and a horizontal asymptote to the right, which can be brought into the above parametric form (here \\$(b,0)\\$ are the coordinates of the center of the hyperbola, \\$2c\\$ is the slope of the slant asymptote, and \\$d\\$ controls how far from the center the hyperbola bends). An evolutionary algorithm was then used to fine-tune the parameters for each sex separately; experiments suggest that there is a single local minimum for each set of data, as all attempts converged to very similar values for \\$b,c,d\\$.

(Technically, the entire function could have been used as the sex indicator, leading to the 4-byte solution `#2@#` with **score 6.1**. But many of the submissions could have done similar things.)
> 2 votes

---
Tags: code-challenge, statistics, approximation
---