title: When will Brexit happen?

text:
# Question
Title: When will Brexit happen?
Well, Brexit happened. And Sky News, being the geniuses they are, have decided to create a countdown on the side of a bus.

Your job is to do something similar. The UK leaves the the EU on 31st of March 2019 and you have to create a digital countdown for this that changes every second (with a 0.05 second deviation allowed).

## Input

Your program should take absolutely no input. It is banned!

## Output

It should output the time until Brexit in the format `ddd:hh:mm:ss`. Leading and trailing newlines are allowed but the display should stay in the same place each time. It should look as though it is actually decreasing in place. As pointed out by @AnthonyPham this doesn't mean printing enough newlines to "clear" the screen, this means that you must actually clear the screen.

An output like this isn't allowed:

```
100:20:10:05
100:20:10:04

```

Neither is this

```
100:20:10:05
*A thousand newlines*
100:20:10:04

```

as they're on more than one line.

You don't have to worry about after Brexit. Your program only has to work up to 31/3/2019

## Rules

* Standard loopholes are disallowed
* This is so shortest code in *bytes* wins.
* Error messages (although I can't think how) are disallowed
* The code should be able to be run in 2 years time (when the UK leaves the EU) and should display the actual time and not start from 730 again (see below)

## Countdown rule

The countdown should not be hard-coded and should be able to run at any time before Brexit finishes and still produce the correct result. When a new day is begun the hour should follow the below format

```
712:00:00:01
712:00:00:00
711:23:59:59

```

Let me say again, the date Brexit finishes is 31/3/2019 at midnight for convenience (31:3:19 00:00:00 or 31:3:2019 00:00:00 or any other format you want)

*NB: I think I have everything but I didn't post this in the Sandbox, otherwise the timing could have been off. Feel free to post any suggestions for improvements because it isn't perfect.*

# Answer
## JavaScript, ~~134~~ ~~129~~ 113 bytes

```
setInterval("d=-new Date;document.body.innerHTML=`<pre>${d/864e5+17986|0}:`+new Date(d).toJSON().slice(11,19)",1)
```

Edit: Saved 2 bytes thanks to @Shaggy. Saved 11 bytes thanks to @l4m2.
> 13 votes

# Answer
# PowerShell, ~~70~~ ~~63~~ ~~55~~ 53 Bytes

Excluded double quotes, easy -2 thanks to @Joey

```
for(){cls;(date 31Mar19)-(date)|% T* ddd\:hh\:mm\:ss}

```

Running this with sleep adds 8 bytes, but the input is mostly invisible if it is run without them, version (63 bytes) with sleep:

```
for(){cls;(date 31/3/19)-(date)|% T* ddd\:hh\:mm\:ss;sleep 1}

```

`for()` is an infinite loop, and within that loop..

`cls` to clear the screen,

get `31/3/19` as a `DateTime` object, and `-` the current date from it, to give the time remaining, then `.ToString()` (`|% T*`) that with the correct format.

this will display negative time after brexit.
> 12 votes

# Answer
# Python 3.6, 146 bytes

```
from datetime import*
x=datetime
while 1:d=x(2019,3,31)-x.now();s=d.seconds;a=s%3600;print(end=f"\r{d.days:03}:{s//3600:02}:{a//60:02}:{s%60:02}")

```
> 7 votes

# Answer
# Excel VBA, ~~91~~ ~~84~~ 82 bytes

Saved 7 bytes thanks to JoeMalpass pointing out that Excel sees dates as numbers.
Saved 2 bytes thanks to JoeMalpass

```
Sub b()
Do
t=CDec(43555-Now)
Cells(1,1)=Int(t) &Format(t,":hh:mm:ss")
Loop
End Sub

```

Output is to cell `A1` in the active Excel sheet.
> 7 votes

# Answer
## C#, ~~173~~ ~~172~~ ~~156~~ ~~150~~ 127 bytes

```
using System;class P{static void Main(){for(;;)Console.Write($"\r{new DateTime(2019,3,31)-DateTime.Now:d\\:hh\\:mm\\:ss}  ");}}

```

*Saved 16 bytes thanks to @Bob* *Saved 6 bytes thanks to @Søren D. Ptæus*

Formatted version:

```
using System;

class P
{
    static void Main()
    {
        for (;;)
            Console.Write($"\r{new DateTime(2019, 3, 31) - DateTime.Now:d\\:hh\\:mm\\:ss}  ");
    }
}

```
> 5 votes

# Answer
# AHK, 145 Bytes

This is not the shortest answer but the result gives a very nice feeling of doom, I think. I originally tried to send the keystrokes `Ctrl`+`A` followed by `DEL` and then whatever the time was but the refresh rate was too slow and it would destroy whatever environment you were in. Instead, then, I went with the GUI. It turned out to take less bytes to completely destroy the window and recreate it than it did to update the control over and over so I went with that. It's a nice effect.

```
Loop{
s=20190331000000
s-=A_Now,S
d:=t:=20000101000000
t+=s,S
d-=t,D
d*=-1
FormatTime f,%t%,:HH:mm:ss
GUI,Destroy
GUI,Add,Text,,%d%%f%
GUI,Show
}

```
> 5 votes

# Answer
# JavaScript ES5, ~~320~~ ~~319~~ ~~316~~ ~~305~~ ~~295~~ 284 bytes

```
setInterval(function(){a=Math,b=a.floor,c=console,d=Date,e="00",f=new d(2019,2,31),g=a.abs(f-new d)/1e3,h=b(g/86400);g-=86400*h;var i=b(g/3600)%24;g-=3600*i;var j=b(g/60)%60;g-=60*j,c.clear(),c.log((e+h).slice(-3)+":"+(e+i).slice(-2)+":"+(e+j).slice(-2)+":"+(e+a.ceil(g)).slice(-2))})
```

Thanks to @Fels for referencing `Math`, @dgrcode for referencing `console`

## Un-golfed

```
setInterval(function() {

  var math = Math, floor = math.floor, c = console, d = Date;

  var leadings = "00";

  // set our brexit date
  var brexit = new d(2019, 2, 31);

  // get total seconds between brexit and now
  var diff = math.abs(brexit - new d()) / 1000;

  // calculate (and subtract) whole days
  var days = floor(diff / 86400);
  diff -= days * 86400;

  // calculate (and subtract) whole hours
  var hours = floor(diff / 3600) % 24;
  diff -= hours * 3600;

  // calculate (and subtract) whole minutes
  var minutes = floor(diff / 60) % 60;
  diff -= minutes * 60;

  // what's left is seconds

  // clear the console (because OP said it must print in the same place)
  c.clear();

  // log the countdown, add the leadings and slice to get the correct leadings 0's
  c.log((leadings + days).slice(-3) + ":" + (leadings + hours).slice(-2) + ":" + (leadings + minutes).slice(-2) + ":" + (leadings + math.ceil(diff)).slice(-2));

});
```
> 4 votes

# Answer
# PHP, 84 bytes

```
for(;$c=DateTime;)echo(new$c('@1553990400'))->diff(new$c)->format("\r%a:%H:%I:%S ");

```

Fairly straightforward. 1553990400 is the timestamp for 31-3-2019 00:00:00 in UTC. It loops infinitely, using DateTime-\>diff()-\>format() to output how much time is left. After Brexit has happened, it will start counting up from 0.

Commented / more readable version:

```
// Infinite loop, assign DateTime (as a string) to $class
for (; $class = DateTime;) {
    echo (new $class('@1553990400')) // Create a new DateTime object for the brexit date/time.
            ->diff(new $class) // Caulculate the difference to the current date/time.
            ->format("\r%a:%H:%I:%S "); // Format it according to the specification, starting with a \r character to move to the start of the line and overwrite the previous output.
}

```
> 4 votes

# Answer
# CJam, ~~69~~ ~~62~~ ~~59~~ 57 bytes

*Saved 7 bytes by converting to time format differently*

*Saved 3 bytes thanks to Martin Ender's suggestions*

*Saved 2 bytes by using a carriage return instead of backspaces*

```
{15539904e5esm1e3/{60md\}2*24md\]W%{sYTe[}%':*CTe[oDco1}g

```

Can't be run on TIO for obvious reasons.

It rewrites the display constantly in an infinite loop so the text kind of flashes in and out (at least in my console), although it only actually updates the time once per second.

This 70-byte version only prints once per second:

```
{15539904e5es:Xm1e3/{60md\}2*24md\]W%{sYTe[}%':*CTe[oDco{esXm1e3<}g1}g

```

**Explanation**

```
{                           e# Begin a while loop
  15539904e5                e#  The timestamp on which Brexit will occur
  es                        e#  The current timestamp
  m                         e#  Subtract
  1e3/                      e#  Integer divide by 1000, converting to seconds from ms
  {                         e#  Run this block twice
   60md                     e#   Divmod by 60
   \                        e#   Swap top elements
  }2*                       e#  (end of block)
                            e#    This block divmods the timestamp by 60, resulting in
                            e#    the remaining minutes and seconds. Then the minutes get
                            e#    divmod-ed by 60, to get hours and minutes remaining
  24md\                     e#  Divmod hours remaining by 24 and swap top elements, to get
                            e#    the hours left and days left.
  ]                         e#  Wrap the entire stack in an array
  W%                        e#  Reverse it since it's currently in the wrong order
  {                         e#  Apply this block to each element of the array
   s                        e#   Cast to string (array of digit characters)
   YTe[                     e#   Pad to length 2 by adding 0s to the left
  }%                        e#  (end of map block)
  ':*                       e#  Join with colons
  CTe[                      e#  Pad to length 12 by adding 0s to the left, dealing with the
                            e#    special case of the day being 3 digits.
  o                         e#  Pop and print the resulting string, which is the time
  Dco                       e#  Print a carriage return, moving the cursor back to the start
  1                         e#  Push 1
}g                          e# Pop 1, if it's true, repeat (infinite loop)

```
> 4 votes

# Answer
# C#6, 149 bytes

*Thanks to Bob for saving 57 bytes!*

```
using System;class P{static void Main(){DateTime a,x=new DateTime(2019,3,31);while((a=DateTime.Now)<x)Console.Write($"\r{x-a:ddd\\:hh\\:mm\\:ss}");}}

```

Ungolfed program:

```
using System;

class P
{
    static void Main()
    {
        DateTime a,
                x = new DateTime(2019, 3, 31);
        while ( (a = DateTime.Now) < x)
            Console.Write($"\r{x-a:ddd\\:hh\\:mm\\:ss}");
    }
}

```

---

# C#, 210 206 159 bytes

*Thanks to Bob for saving another 47 bytes!*

*Thanks to Martin Smith for saving 4 bytes!*

```
using System;class P{static void Main(){DateTime a,x=new DateTime(2019,3,31);while((a=DateTime.Now)<x)Console.Write("\r"+(x-a).ToString(@"ddd\:hh\:mm\:ss"));}}

```

Ungolfed program:

```
using System;

class P
{
    static void Main()
    {
        DateTime a,
                x = new DateTime(2019, 3, 31);
        while ( (a = DateTime.Now) < x)
            Console.Write("\r" + (x - a).ToString(@"ddd\:hh\:mm\:ss"));
    }
}

```
> 3 votes

# Answer
# Python 3.5 (118 Bytes)

```
import datetime as d,os
d=d.datetime
while 1:os.system("cls");e=str(d(2019,3,31)-d.today());print(e[:3]+':'+e[-15:-7])

```
> 3 votes

# Answer
## Ruby (83 bytes)

```
loop{h=431664-Time.now.to_r/3600;$><<['%02d']*4*?:%[h/24,h%24,h%1*60,h*3600%60]+?\r}

```

## Ungolfed

```
loop do
  seconds = 1553990400 - Time.now.to_r

  print (["%02d"] * 4).join(':') % [
    seconds / 24 / 60 / 60     ,
    seconds      / 60 / 60 % 24,
    seconds           / 60 % 60,
    seconds                % 60,
  ] + "\r"
end

```

Basically one of the Python submissions, with some improvements. We just emit an "\r" to go beginning of the string before re-rendering. And for the string format of `"%03d:%02d:%02d:%02d"`, we really don't care about the width on the first specifier… so we can just do `"%02d"*4`, and emit a backspace and a space to clear the extra unnecessary colon.

Also, I found a two-character shorter `print`: `$><<`. `$>` is a shorthand global for `$defout`, which is the output stream for `print` and `printf` and defaults to `STDOUT`. `IO#<<` writes the right hand side of it to the stream. How is that two characters shorter? Well, I can now omit the space that led before the parenthesis wrapping the format string.

At this point I genuinely think there is no possible way to shorten this program further in Ruby.

Edit: I was wrong. Instead of the first `Time.new(2019,3,31)`, we can just use the raw UNIX time: `1553990400`.

Edit 2: I've tried playing around with factoring out minutes, and dividing the UNIX timestamp by that constant, but it doesn't actually wind up saving any bytes. :(

Edit 3: Turns out caching `h=3600` actually hurt me by two bytes. Whoops.

Edit 4: Saved 3 bytes thanks to @EricDuminill. He used floats, but rationals work without loss of precision!

Edit 5: `Array#*` as an alias for `Array#join`, with the Ruby `?`-syntax for individual characters!
> 3 votes

# Answer
# C, 104 bytes

```
main(x){for(;x=1553990400-time(0);)printf("\n%03d:%02d:%02d:%02d\e[1A",x/86400,x/3600%24,x/60%60,x%60);}

```

### Breakdown

```
main(x){
    for(;x=1553990400-time(0);)             // Seconds remaining
        printf("\n%03d:%02d:%02d:%02d\e[1A",// Move cursor and print:
            x/86400,                        // Days
            x/3600%24,                      // Hours
            x/60%60,                        // Minutes
            x%60);                          // Seconds
    puts("Now we can stop talking about it forever."); // Wishful thinking
}

```

Relies on `time` returning number of seconds since 01/01/1970, which is the case for me (using Clang/GCC on macOS) and should be the case for most UNIX stuff.

Uses ~~bash~~ terminal escape sequences to move the cursor around (`<esc>[1A` moves the cursor up 1 line). It would be nicer to be able to simply use `\r`, but `printf` won't flush until it sees a newline, and flushing it manually takes a lot more.

Probably the most CPU intensive countdown I've ever seen. Runs in a hot loop to make sure it's always as accurate as can be. If run after the deadline, it will produce some pretty weird stuff (negatives everywhere!)
> 3 votes

# Answer
# C#, 128 127 Bytes

```
using System;class P{static void Main(){for(;;)Console.Write($"\r{new DateTime(2019,3,31)-DateTime.Now:ddd\\:hh\\:mm\\:ss}");}}

```

Ungolfed code:

```
using System;
class P
{
    static void Main()
    {
        for(;;)
            Console.Write($"\r{new DateTime(2019,3,31)-DateTime.Now:ddd\\:hh\\:mm\\:ss}");
    }
}

```

I would not have figured out the \r trick without help from the other C# answers here.

For anyone looking for further improvement, you can also put the Write() expression inside the for loop. Seems like I should be able to save a byte somehow here, because that saves me the semi-colon for that statement, but it works out to the same number because you can't have a fully empty body:

```
using System;class P{static void Main(){for(;;Console.Write($"\r{new DateTime(2019,3,31)-DateTime.Now:ddd\\:hh\\:mm\\:ss}"));}}

```
> 3 votes

# Answer
# Bash + GNU date, 128 bytes

*2 bytes shaved off thanks to @muru, and 2 off earlier thanks to @This Guy.*

```
C=:%02d;while sleep 1;do D=$[B=3600,A=24*B,1553990400-`date +%s`];printf "%03d$C$C$C\r" $[D/A] $[D%A/B] $[D%A%B/60] $[D%60];done

```

### Ungolfed

```
DAY=86400
HOUR=3600
while sleep 1 ; do
 DIFF=$[1553990400-`date +%s`]
 printf "%03d:%02d:%02d:%02d\r" \
         $[DIFF/DAY] \
         $[DIFF%DAY/HOUR] \
         $[DIFF%DAY%HOUR/60] \
         $[DIFF%60]
done

```
> 2 votes

# Answer
## JavaScript+HTML, 136+7=143 bytes

```
setInterval("d=1553990400-new Date/1e3|0;w.innerText=[60,60,24,999].map(z=>(q='00'+d%z,d=d/z|0,q.slice(z<61?-2:-3))).reverse().join`:`")

```

```
<a id=w

```
> 2 votes

# Answer
# C#, 142 bytes

```
using System;class P{static void Main(){a:Console.Write($"\r{(new DateTime(2019,3,31)-DateTime.Now).ToString("d\\:h\\:mm\\:ss  ")}");goto a;}}

```

Ungolfed program:

```
using System;
class P
{
    static void Main()
    {
        a: Console.Write($"\r{(new DateTime(2019, 3, 31) - DateTime.Now).ToString(@"d\:h\:mm\:ss  ")}"); goto a;
    }
}

```
> 2 votes

# Answer
# MATL, 45 bytes

```
737515`tZ'-tkwy-':HH:MM:SS'XOw'%03d'YDwYcDXxT

```

TIO apparently doesn't support clearing the output, but thankfully MATL Online does!

At 2 bytes more, a bit more CPU-friendly version that does a `pause` (sleep) every second:

```
737515`tZ'-tkwy-':HH:MM:SS'XOw'%03d'YDwYcDT&XxT

```

Try this on MATL Online

`737515` is "31st of March 2019" represented MATLAB's default epoch format - number of days from January 0, 0000, optionally including a fractional part to represent the time of day. (I tried to shorten this by calculating it somehow, but its only factors are 5 and another six digit number (147503), and I couldn't figure out a way to do it in less than 6 bytes.)

```
`    % start do-while loop
tZ`- % duplicate Brexit date, get current date (& time), subtract
tk   % duplicate the difference, get the floor of it (this gives number of days left)
w    % switch stack to bring unfloored difference to top
y    % duplicate the floored value on top of that
-    % subtract to get fractional part representing time
':HH:MM:SS'XO % get a datestr (date string) formatted this way
w    % switch to bring number of days back on top
'%03d'YD      % format that to take 3 places, with 0 padding if needed
wYc  % switch to bring time string back on top, concatenate date and time
D    % display the concatenated result!
T&Xx % clear screen after a 1 second pause (the pause is optional, without it the call is `Xx`)
T    % push True on stack to continue loop

```
> 2 votes

# Answer
# Phooey, 101 bytes

```
-1(>"`\e`[H"~t/1000;1554004800@%60>&/60@%60>&/60@%24>&/24@@/100{$i}&/10{$i}&$i<(_1":"@/10{$i}&$i<)"
"#1)
```

`\e` represents the `ESC` nonprintable, hex `0x1B`. Requires your average Linux terminal (and I believe it may work on Windows with a recent command prompt). Phooey does not support C-style escapes, the bytes must be verbatim or you must use `$cN`.

```
-1            # set sentinel cell
(             # do {..} while (*cell) (infinite loop)
  >           #   move past our sentinel
  "`\e`[H"     #   print "clear" ANSI escape code
  ~t          #   get current Unix time in milliseconds
  /1000       #   convert to seconds
  ;1554004800 #   31 Mar 2019 in Unix time - *cell
  @           #   Push a copy
  %60         #   Store seconds in the first cell
  >&          #   Move to the next cell
  /60         #   Convert to minutes
  @           #   Push a copy
  %60         #   Store minutes in the second cell
  >&/60@%24>  #   ya get the point
  &/24        #   get the number of days
  @@          #   begin ugly zero pad code
  /100{$i}    #   if intdiv(days, 100) == 0, print 0
  &/10{$i}    #   repeat for tens place
  &$i         #   print value
  <           #   go to hours place
  (_1         #   do {..} while not -1 (our sentinel)
    ":"       #     print ":"
    @/10{$i}  #     zero pad
    &$i       #     print digit
    <         #     go to prev cell
  )           #   loop till sentinel
  "`\n`"       #   print new line to flush stdout
  #1          #   wait one second otherwise your terminal will flip out
)             # loop forever
```

It does fail miserably for dates after Brexit thanks to signed division lul:

```
-689:0-8:-44:-37

```

But for dates before Brexit, it is correct.

For a version which sets to zero after Brexit, (at the cost of a memory leak and 9 bytes), here you go:

```
-1(>"`\e`[H"~t/1000;1554004800**@@&2^{@}&**@%60>&/60@%60>&/60@%24>&/24@@/100{$i}&/10{$i}&$i<(_1":"@/10{$i}&$i<)"
"#1)
```

Specifically, this code uses some fancy math to check for negative.

```
@@&2^{@}&

```

(Or `*@` to patch the memory leak which pops, multiplies by zero, then pushes)

It uses the `pow` operator.

Specifically, `^` does this:

```
    *cell = (int64_t)pow(*cell, op);

```

So, in equivalent C, this code would be:

```
int64_t positive_or_zero(int64_t val)
{
    int64_t pwr = (int64_t)pow(2, val);
    if (pwr == 0) {
        val = pwr;
    }
    return val;
}

```

`pow` is a function which accepts and returns `double`, however, we downcast this.

People who are familiar with how double conversion works will know that infinity converts to `0x8000000000000000`, and fractions between 0 and 1 will be zero.

Additionally, \\${2}^{x}\\$ will always be a number greater than 1 if \\$x \>= 0\\$, and a positive fraction less than 1 if \\$x \< 0\\$.

Therefore, if `^` returns 0, we know that \\$x\\$ is negative. Then, we just push it to the stack.
> 2 votes

# Answer
# PHP, 64 bytes

```
while($d=1553990401-time())echo--$d/86400|0,date(":H:i:s\r",$d);

```

This will count exactly until `0:00:00:00` and then break/exit. Run with `-r`.

-2 bytes if I wouldn´t have to print the 0.
> 1 votes

# Answer
# RPL, 83 78 bytes

Assuming your HP48, or similar, is setup with correct (UK) time and date, mm/dd date format, and 24h time format:

```
WHILE 1REPEAT DATE 3.302019DDAYS":"1.1 24TIME HMS- TSTR 15 23SUB + + 1DISP END

```

I was surprised to be able to save 2 bytes by removing spaces around `":"`. 1.1 is the shortest valid date, later dumped by `SUB`. Be careful with emulators, the time may run faster or slower (or not at all) than your wall clock. With a real HP, you can stop this program by pressing the ON key … or wait for empty batteries.
> 1 votes

# Answer
# SlimSharp, 56 bytes

```
for(;;)P($"{TP("2019-3-31")-T.Now:ddd\\:hh\\:mm\\:ss}");

```
> 1 votes

# Answer
# PHP, 102 95 90 bytes

*Saved 7 bytes thanks to @TheLethalCoder & by not factoring*

*Saved another 5 bytes by concatenating*

```
<? $b=1553990400-time();echo floor($b/$d=86400).date(':H:i:s', $b%$d);header('Refresh:1');

```

This is my first golf, so I'm probably missing quite a few tricks, but here you are regardless.

As for @chocochaos' PHP answer that would otherwise trump this, I believe it is flawed for reasons I have explained in my comments, but as I'm new here I might be wrong. Or I'm just a newbie :)
> 0 votes

# Answer
# AWK, 78 bytes

```
BEGIN{for(;v=1552953600-systime();printf"\r%d:%s",v/86400,strftime("%T",v)){}}

```

Try it online!

Was longer before I realized I could precalculate the end time. Sometimes it pays to be a bit late to the game and get ideas from others.

FYI, the TIO link doesn't work very well, since it doesn't implement `\r` properly.
> 0 votes

# Answer
# F#, 142 bytes

```
open System
let f=
 let t=DateTime(2019,3,31)
 while DateTime.Now<=t do Console.Clear();t-DateTime.Now|>printf"%O";Threading.Thread.Sleep 1000

```

I grew up in Ireland about half a kilometre from the border. Apart from a "Welcome to Fermanagh" sign and the road markings changing you wouldn't know you'd entered another country. Used to cross it twice on the way to school.
> 0 votes

# Answer
# c, gcc 114 bytes

```
main(s){system("clear");if(s=1553900399-time(0)){printf("%d:%d:%d:%d\n",s/86400,s/3600%24,s/60%60,s%60);main(s);}}

```

Nothing omitted, full program. The program compiles in gcc on Ubuntu. The countdown will not show a long trail of print statements because of the system call to clear and halts when the countdown reaches 0 seconds.

# UnGolfed

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

//Brexit countdown timer
int main(){
  int sec = 1553900400 - time(0);//seconds remaining until Brexit
  if(sec){
    sleep(1);
    system("clear");
    printf("Brexit Countdown\n");
    printf("days Hours Mins Secs\n");
    printf("%d:  %d:    %d:  %d\n",
            sec/86400, sec/3600%24,
            sec/60%60, sec%60);
    main();
  }
}

```
> 0 votes

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


title: Sum Chain Sequence

text:
# Question
Title: Sum Chain Sequence
**Sequence:**

1. We start at `1`.
2. We first add the current 1-indexed value to the previous number in the sequence.
3. Then we apply the following mathematical operations in order if they apply to this current value:
    * Divisible by `2`? =\> Addition
    * Divisible by `3`? =\> Subtraction
    * Divisible by `4`? =\> (Addition AND) Multiply
    * Not divisible by neither `2`, `3` nor `4`? -\> Continue with current sum-result

**Output:**

Output the first 100 numbers in this sequence:

```
1, 1, 21, 25, 30, 216, 223, 223, 2169, 2179, 2190, 2202, 2215, 2215, 2245, 2261, 2295, 2295, 2333, 2353, 2395, 2417, 56649, 56649, 56699, 56725, 1533033, 1533061, 1533090, 45993600, 45993631, 45993631, 1517792001, 1517792035, 1517792070, 1517792106, 1517792143, 1517792143, 1517792221, 1517792261, 1517792343, 1517792343, 1517792429, 1517792473, 1517792563, 1517792609, 71336257041, 71336257041, 71336257139, 71336257189, 3638149121841, 3638149121893, 3638149121946, 196460052588000, 196460052588055, 196460052588055, 11198222997525633, 11198222997525691, 11198222997525750, 11198222997525810, 11198222997525871, 11198222997525871, 11198222997525997, 11198222997526061, 11198222997526191, 11198222997526191, 11198222997526325, 11198222997526393, 11198222997526531, 11198222997526601, 795073832824398753, 795073832824398753, 795073832824398899, 795073832824398973, 59630537461829934225, 59630537461829934301, 59630537461829934378, 4651181922022734887568, 4651181922022734887647, 4651181922022734887647, 376745735683841525912529, 376745735683841525912611, 376745735683841525912694, 376745735683841525912778, 376745735683841525912863, 376745735683841525912863, 376745735683841525913037, 376745735683841525913125, 376745735683841525913303, 376745735683841525913303, 376745735683841525913485, 376745735683841525913577, 376745735683841525913763, 376745735683841525913857, 35790844889964944961834465, 35790844889964944961834465, 35790844889964944961834659, 35790844889964944961834757, 3543293644106529551221660545, 3543293644106529551221660645

```

**Here are the first 10 numbers in the sequence with explanation:**

```
// Starting number of the sequence:
1

// 1 (previous number in the sequence)
// + 2 (current index in 1-indexed sequence)
// = 3 -> 3 - 2 (3 is divisible by 3, so we subtract the current index 2)
// = 1
1

// 1 (previous number in the sequence)
// + 3 (current index in 1-indexed sequence)
// = 4 -> 4 + 3 (4 is divisible by 2, so we first add the current index 3)
// = 7 -> 7 * 3 (and 4 is also divisible by 4, so we then also multiply the current index 3)
// = 21
21

// 21 (previous number in the sequence)
// + 4 (current index in 1-indexed sequence)
// = 25 (25 is not divisible by 2, 3 nor 4)
25

// 25 (previous number in the sequence)
// + 5 (current index in 1-indexed sequence)
// = 30 -> 30 + 5 (30 is divisible by 2, so we first add the current index 5)
// = 35 -> 35 - 5 (and 30 is also divisible by 3, so we then also subtract the current index 5)
// = 30
30

// 30 (previous number in the sequence)
// + 6 (current index in 1-indexed sequence)
// = 36 -> 36 + 6 (36 is divisible by 2, so we first add the current index 6)
// = 42 -> 42 - 6 (and 36 is also divisible by 3, so we then also subtract the current index 6)
// = 36 -> 36 * 6 (and 36 is also divisible by 4, so we then also multiply the current index 6)
// = 216
216

// 216 (previous number in the sequence)
// + 7 (current index in 1-indexed sequence)
// = 223 (223 is not divisible by 2, 3 nor 4)
223

// 223 (previous number in the sequence)
// + 8 (current index in 1-indexed sequence)
// = 231 -> 231 - 8 (231 is divisible by 3, so we subtract the current index 8)
// = 223
223

// 223 (previous number in the sequence)
// + 9 (current index in 1-indexed sequence)
// = 232 -> 232 + 9 (232 is divisible by 2, so we first add the current index 9)
// = 241 -> 241 * 9 (and 232 is also divisible by 4, so we then also multiply the current index 9)
// = 2169
2169

// 2169 (previous number in the sequence)
// + 10 (current index in 1-indexed sequence)
// 2179 (2179 is not divisible by 2, 3 nor 4)
2179

```

**Challenge rules:**

* If your language doesn't support anything bigger than 231-1, you can continue the sequence until that max (so the first 46 numbers, up until - and including - `1,517,792,609`).
* The output format is flexible. You can return an array or list, a string separated with spaces, commas, etc. Your call.

**General rules:**

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.

# Answer
> 1 votes
# 05AB1E, ~~24~~ 23 bytes

*-1 byte thanks to Kevin Crujissen*

```
¼¾тF=¼¾+©…+-*v®NÌÖi¾y.V

```

Try it online!

Explanation:

```
¼¾                        # set the counter to 1, then push 1
  тF                      # repeat the following 100 times
    =                     # print the current number in the sequence
     ¼¾                   # increment the counter
       +                  # add it to the current number
        ©                 # save the result in the register
         …+-*v            # for each of '+', '-', and '*'...
              ®   i       # if the register...
                 Ö        # is divisible by...
               NÌ         # the loop index + 2...
                   ¾y.V   # then apply the current operation

```

# Answer
> 8 votes
# R, ~~85~~ ~~82~~ ~~79~~ ~~76~~ ~~72~~ 70 bytes

```
for(i in 2:56)T[i]=((z=i+T[i-1])+i*(!z%%2)-i*(!z%%3))*`if`(z%%4,1,i);T

```

ungolfed:

```
s=1 ## formerly s=1:56, formerly s=1:100
for(i in 2:56){
    z=i+s[i-1]
    s[i]=(z+i*(z%%2<1)-i*(z%%3<1))*(1+(i-1)*(z%%4<1))
}
s

```

Thanks to @rturnbull for pointing out that I can use `(!z%%3)` instead of `(z%%3<1)` to check the moduli, and that the definition of `z` an happen when it is first used.

Golfed away 3-4 chars by abusing vector extension: the answer originally started `s=1:56...` but we don't need to do that, the length of `s` will be extended as needed.

Saved 3 more bytes by replacing the last condition with a call to the `"if"` function (yes, it's a proper function in R!)

Saved 4 more bytes by replacing `s` with `T`, which is a builtin equal to `TRUE` which is also equal to `1`. I realised it at the same time as @rturnbull (honest!)

This does suffer from some numerical issues once we exceed 2^52, but there is nothing I can do about that --- R can only use `double` types for numbers larger than `2^31-1`, but they store integers up to 2^52 exactly. Thus, I am allowed to only output the first 56 terms (the last term which is "right") which saves one byte over the 100-length case.

Here's the output from the 56-length version:

```
    > for(i in 2:56){z=i+T[i-1];T[i]=(z+i*(!z%%2)-i*(!z%%3))*`if`(z%%4,1,i)};T
 [1]               1               1              21              25              30             216
 [7]             223             223            2169            2179            2190            2202
[13]            2215            2215            2245            2261            2295            2295
[19]            2333            2353            2395            2417           56649           56649
[25]           56699           56725         1533033         1533061         1533090        45993600
[31]        45993631        45993631      1517792001      1517792035      1517792070      1517792106
[37]      1517792143      1517792143      1517792221      1517792261      1517792343      1517792343
[43]      1517792429      1517792473      1517792563      1517792609     71336257041     71336257041
[49]     71336257139     71336257189   3638149121841   3638149121893   3638149121946 196460052588000
[55] 196460052588055 196460052588055

```

# Answer
> 5 votes
# Python 3, ~~82~~ ~~78~~ ~~76~~ ~~74~~ 72 bytes

```
i=s=1
exec('print(s);i+=1;s+=i;s=(s+i-i*(s%2+(s%3<1)))*i**(s%4<1);'*100)

```

Output:

```
1
1
21
25
30
216
223
223
2169
2179
2190
2202
2215
2215
2245
2261
2295
2295
2333
2353
2395
2417
56649
56649
56699
56725
1533033
1533061
1533090
45993600
45993631
45993631
1517792001
1517792035
1517792070
1517792106
1517792143
1517792143
1517792221
1517792261
1517792343
1517792343
1517792429
1517792473
1517792563
1517792609
71336257041
71336257041
71336257139
71336257189
3638149121841
3638149121893
3638149121946
196460052588000
196460052588055
196460052588055
11198222997525633
11198222997525691
11198222997525750
11198222997525810
11198222997525871
11198222997525871
11198222997525997
11198222997526061
11198222997526191
11198222997526191
11198222997526325
11198222997526393
11198222997526531
11198222997526601
795073832824398753
795073832824398753
795073832824398899
795073832824398973
59630537461829934225
59630537461829934301
59630537461829934378
4651181922022734887568
4651181922022734887647
4651181922022734887647
376745735683841525912529
376745735683841525912611
376745735683841525912694
376745735683841525912778
376745735683841525912863
376745735683841525912863
376745735683841525913037
376745735683841525913125
376745735683841525913303
376745735683841525913303
376745735683841525913485
376745735683841525913577
376745735683841525913763
376745735683841525913857
35790844889964944961834465
35790844889964944961834465
35790844889964944961834659
35790844889964944961834757
3543293644106529551221660545
3543293644106529551221660645

```

Suggestions are welcome!

# Answer
> 4 votes
# 05AB1E, ~~34~~ ~~31~~ 30 bytes

```
XTnFD,NÌ©+D3L>%_`X®‚sèrŠs-®*+*

```

Try it online!

**Explanation**

```
X                               # initialize stack with 1
 TnF                            # for N in [0 ... 99]
    D,                          # print a copy of top of stack
      NÌ©                       # increase index N by 2 and store in register
         +                      # add this to current value
          D                     # make a copy of the current value
           3L>                  # push the list [2,3,4]
              %                 # take current value mod elements in list
               _                # invert this
                `               # push the elements from the list to stack
                 X®‚sè          # index into list [1,N+2] with the result of mod 4
                      rŠs-      # subtract result of mod 3 from result of mod 2
                          ®*    # multiply by N+2
                            +   # add this to current value
                             *  # multiply current value with the result from index operation

```

# Answer
> 3 votes
# Python 2, 76 Bytes

Pretty standard implementation, I think using an exec statement rather than a while loop saved 2 bytes or so. A recursive method may be shorter, I imagine xnor will pop up soon ;)

```
n=1
f=1
exec'print f;n+=1;d=f+n;f=(d+n*(d%2<1)-n*(d%3<1))*[1,n][d%4<1];'*100

```

If I used the updates that TheNumberOne figured out, I would be at 69 bytes (but then I would be copying)

```
n=f=1;exec'print f;n+=1;d=f+n;f=(d+n-n*(d%2+(d%3<1))*n**(d%4<1);'*100

```

Output:

```
1
1
21
25
30
216
223
223
2169
2179
2190
2202
2215
2215
2245
2261
2295
2295
2333
2353
2395
2417
56649
56649
56699
56725
1533033
1533061
1533090
45993600
45993631
45993631
1517792001
1517792035
1517792070
1517792106
1517792143
1517792143
1517792221
1517792261
1517792343
1517792343
1517792429
1517792473
1517792563
1517792609
71336257041
71336257041
71336257139
71336257189
3638149121841
3638149121893
3638149121946
196460052588000
196460052588055
196460052588055
11198222997525633
11198222997525691
11198222997525750
11198222997525810
11198222997525871
11198222997525871
11198222997525997
11198222997526061
11198222997526191
11198222997526191
11198222997526325
11198222997526393
11198222997526531
11198222997526601
795073832824398753
795073832824398753
795073832824398899
795073832824398973
59630537461829934225
59630537461829934301
59630537461829934378
4651181922022734887568
4651181922022734887647
4651181922022734887647
376745735683841525912529
376745735683841525912611
376745735683841525912694
376745735683841525912778
376745735683841525912863
376745735683841525912863
376745735683841525913037
376745735683841525913125
376745735683841525913303
376745735683841525913303
376745735683841525913485
376745735683841525913577
376745735683841525913763
376745735683841525913857
35790844889964944961834465
35790844889964944961834465
35790844889964944961834659
35790844889964944961834757
3543293644106529551221660545
3543293644106529551221660645

```

# Answer
> 3 votes
# JavaScript, ~~75~~ 63 bytes

```
for(n=p=0;n++<57;alert(p=p%4?q:q*n))q=(p+=n)%2?p:p+n,q-=p%3?0:n

```

Another version:

```
for(n=p=0;n++<57;)alert(p=((p+=n)+(!(p%2)-!(p%3))*n)*(p%4?1:n))

```

Both stop at index 57 (0-indexed) because that's when the output surpasses JavaScript's safe number size (253 \- 1). Turns out a loop is way shorter than a recursive function, even with ES6:

```
f=(n=0,p=0)=>n++>56?[]:(q=(p+=n)%2?p:p+n,q-=p%3?0:n,[q*=p%4?1:n,...f(n,q)])

```

This one returns an array of the first 57 elements.

# Answer
> 3 votes
# Brain-Flak ~~476 466 462 456~~ 446 Bytes

Saved 6 bytes thanks to Wheat Wizard

```
(((((((())<>()(())()){}){}){}())){}{}){({}[()]<(((({})<>({}())<>))<({}(()())(<()>)){({}[()]<(({}()[({})])){{}(<({}({}))>)}{}>)}({}{}<{}(())>){((<{}{}>))}{}{(<{}({}<>({})<>)>)}{}>)(({})<({}(()()())(<()>)){({}[()]<(({}()[({})])){{}(<({}({}))>)}{}>)}({}{}<{}(())>){((<{}{}>))}{}{(<{}({}<>[({})]<>)>)}{}>)({}(()()()())(<()>)){({}[()]<(({}()[({})])){{}(<({}({}))>)}{}>)}({}{}<{}(())>){((<{}{}>))}{}{(<{}(<>({}))({<({}[()])><>({})<>}{}<><{}>)>)}{}>)}{}

```

Try it Online!

This is really slow. TIO can't handle the whole 100 numbers (the limit seems to be 22 or 23). So, this example only generates the first 20, but the code would work for 100 as well.

**Brief Explanation:**

```
      (())<>                           # push a 1 (the index) and switch stacks
            (())                       # then push a 1 (the starting number)
((((((          ()()){}){}){}())){}{}) # and a 99 (a counter so that we only print the
                                       # first 100 numbers)

# repeat until the counter is 0
{
  # pop the counter and push it minus 1 after:
  ({}[()]<
    # hold onto the current number plus the index (leave a copy on the stack to be printed)
    # and increment the index
    (((({})<>({}())<>))<
      # push logical not of (current mod 2)
      ({}(()())(<()>)){({}[()]<(({}()[({})])){{}(<({}({}))>)}{}>)}({}{}<{}(())>){((<{}{}>))}{}
      # if !(current mod 2) is 1, add the index
      {(<{}({}<>({})<>)>)}{}
    # push the current number back on
    >)
    # hold onto the current number
    (({})<
     # push logical not of (current mod 3)
     ({}(()()())(<()>)){({}[()]<(({}()[({})])){{}(<({}({}))>)}{}>)}({}{}<{}(())>){((<{}{}>))}{}
     # if !(current mod 3) is 1, then subtract the index
     {(<{}({}<>[({})]<>)>)}{}
    # push the current number back on
    >)
    # push logical not of (current mod 4)
    ({}(()()()())(<()>)){({}[()]<(({}()[({})])){{}(<({}({}))>)}{}>)}({}{}<{}(())>){((<{}{}>))}{}
    # if !(current mod 4) is 1, multiply by the index
    {(<{}(<>({}))({<({}[()])><>({})<>}{}<><{}>)>)}{}
  # put the counter back on
  >)
# loop until done
}
# pop the counter
{}

```

# Answer
> 1 votes
# Java 7, 316 bytes

```
import java.math.*;String c(){String r="";BigInteger t=BigInteger.ONE,x,p;for(int i=2;i<102;){r+=t+" ";p=(t=t.add(x=new BigInteger(i+++"")));t=x(p,2)?t.add(x):t;t=x(p,3)?t.subtract(x):t;t=x(p,4)?t.multiply(x):t;}return r;}boolean x(BigInteger p,int i){return p.mod(new BigInteger(i+"")).compareTo(BigInteger.ONE)<0;}

```

**Ungolfed & test code:**

Try it here.

```
import java.math.*;
class M{
  static String c(){
    String r = "";
    BigInteger t = BigInteger.ONE,
               x,
               p;
    for(int i = 2; i < 102;){
      r += t+" ";
      p = (t = t.add(x = new BigInteger(i++ + "")));
      t = x(p, 2)
           ? t.add(x)
           : t;
      t = x(p, 3)
           ? t.subtract(x)
           : t;
      t = x(p, 4)
           ? t.multiply(x)
           : t;
    }
    return r;
  }

  public static void main(String[] a){
    System.out.println(c());
  }

  static boolean x(BigInteger p, int i){
    return p.mod(new BigInteger(i+"")).compareTo(BigInteger.ONE) < 0;
  }
}

```

**Output:**

```
1 1 21 25 30 216 223 223 2169 2179 2190 2202 2215 2215 2245 2261 2295 2295 2333 2353 2395 2417 56649 56649 56699 56725 1533033 1533061 1533090 45993600 45993631 45993631 1517792001 1517792035 1517792070 1517792106 1517792143 1517792143 1517792221 1517792261 1517792343 1517792343 1517792429 1517792473 1517792563 1517792609 71336257041 3424140340272 3424140340321 3424140340371 3424140340473 3424140340525 3424140340631 3424140340631 3424140340741 3424140340797 3424140340911 3424140340969 202024280124133 202024280124193 202024280124315 202024280124377 12727529647843689 814561897462000192 52946523335030016705 52946523335030016771 52946523335030016905 52946523335030016973 52946523335030017111 52946523335030017111 52946523335030017253 52946523335030017253 52946523335030017399 52946523335030017473 3970989250127251321725 301795183009671100456876 301795183009671100456953 301795183009671100457031 301795183009671100457110 301795183009671100457270 301795183009671100457351 301795183009671100457433 25049000189802701337980717 25049000189802701337980801 25049000189802701337980971 25049000189802701337981057 2179263016512835016404367097 191775145453129481443584312280 17067987945328523848479003800841 1536118915079567146363110342083790 1536118915079567146363110342083790 1536118915079567146363110342083974 1536118915079567146363110342083974 144395178017479311758132372155911228 13717541911660534617022575354811575685 13717541911660534617022575354811575781 13717541911660534617022575354811575975 13717541911660534617022575354811576073 1358036649254392927085234960126346050829

```

# Answer
> 1 votes
# C#, 120 Bytes

Just as no sane person would golf in Java, no sane person should golf in C#! But screw that, I wanted to see what I can do. The `1M` casts `f` to be a decimal which has enough precision for this answer without me having to write `decimal`. Also, the in-place incrementing saves some bytes on my Python answer. in the end it is still 50 bytes longer.

```
void k(){int n=1;var f=1M;while(n<101){Console.WriteLine(f);var d=++n+f;f=(d+n*((d%2<1?1:0)-(d%3<1?1:0)))*(d%4<1?n:1);}}

```

Here's the more readable (and runnable) version:

```
using System;
class P
{
    static void Main(string[]a)
    {
        int n = 1;
        var f = 1M;
        while (n < 101)
        {
            Console.WriteLine(f);
            var d = ++n + f;
            f = (d + n * ((d % 2 < 1 ? 1 : 0) - (d % 3 < 1 ? 1 : 0))) * (d % 4 < 1 ? n : 1);
        }
        Console.Read();
    }
}

```

# Answer
> 1 votes
## Batch, 110 bytes

```
@set n=0
@for /l %%i in (1,1,46)do @set/an=((n+=%%i)+(!(n%%2)-!(n%%3))*%%i)*(~-%%i*!(n%%4)+1)&call echo %%n%%

```

Uses @ETHproductions' formula, but tweaked slightly because Batch doesn't have `?:`. Batch uses 32-bit signed integers so the loops stops at 46.

# Answer
> 1 votes
# Perl, 75 Bytes

```
use bigint;$a+=$_,say$a=($a+($a%2?0:$_)-($a%3?0:$_))*($a%4?1:$_)for(1..100)

```

The code outputs each value on a new line, and computes all 100 values.

# Answer
> 1 votes
## Haskell, ~~70~~ 64 bytes

```
a%b=0^mod a b
n#i|s<-n+i=(s+s%2*i-s%3*i)*i^s%4
scanl1(#)[1..100]

```

`scanl1(#)[1..100]` returns the list with the first 100 elements. One byte less if I can stay in the 2^31 range (-\> `[1..46]`).

`scanl1` is like `foldl1` but collects the intermediate results in a list. The divisibility tests are done via the helper function `%` which returns `0^0 = 1` if divisible and `0^x = 0` if not.

# Answer
> 1 votes
# J, 46 bytes

```
(,{:((]^0=4|+)*(]*0=2|+)++-]*0=3|+)1+#)^:99]1x

```

Applies the method described in the challenge.

## Usage

The extra command `(,.~#\)` is used to add indices to each value.

```
   (,.~#\) (,{:((]^0=4|+)*(]*0=2|+)++-]*0=3|+)1+#)^:99]1x
  1                            1
  2                            1
  3                           21
  4                           25
  5                           30
  6                          216
  7                          223
  8                          223
  9                         2169
 10                         2179
 11                         2190
 12                         2202
 13                         2215
 14                         2215
 15                         2245
 16                         2261
 17                         2295
 18                         2295
 19                         2333
 20                         2353
 21                         2395
 22                         2417
 23                        56649
 24                        56649
 25                        56699
 26                        56725
 27                      1533033
 28                      1533061
 29                      1533090
 30                     45993600
 31                     45993631
 32                     45993631
 33                   1517792001
 34                   1517792035
 35                   1517792070
 36                   1517792106
 37                   1517792143
 38                   1517792143
 39                   1517792221
 40                   1517792261
 41                   1517792343
 42                   1517792343
 43                   1517792429
 44                   1517792473
 45                   1517792563
 46                   1517792609
 47                  71336257041
 48                  71336257041
 49                  71336257139
 50                  71336257189
 51                3638149121841
 52                3638149121893
 53                3638149121946
 54              196460052588000
 55              196460052588055
 56              196460052588055
 57            11198222997525633
 58            11198222997525691
 59            11198222997525750
 60            11198222997525810
 61            11198222997525871
 62            11198222997525871
 63            11198222997525997
 64            11198222997526061
 65            11198222997526191
 66            11198222997526191
 67            11198222997526325
 68            11198222997526393
 69            11198222997526531
 70            11198222997526601
 71           795073832824398753
 72           795073832824398753
 73           795073832824398899
 74           795073832824398973
 75         59630537461829934225
 76         59630537461829934301
 77         59630537461829934378
 78       4651181922022734887568
 79       4651181922022734887647
 80       4651181922022734887647
 81     376745735683841525912529
 82     376745735683841525912611
 83     376745735683841525912694
 84     376745735683841525912778
 85     376745735683841525912863
 86     376745735683841525912863
 87     376745735683841525913037
 88     376745735683841525913125
 89     376745735683841525913303
 90     376745735683841525913303
 91     376745735683841525913485
 92     376745735683841525913577
 93     376745735683841525913763
 94     376745735683841525913857
 95   35790844889964944961834465
 96   35790844889964944961834465
 97   35790844889964944961834659
 98   35790844889964944961834757
 99 3543293644106529551221660545
100 3543293644106529551221660645

```

# Answer
> 1 votes
# Perl 6, 62 bytes

```
1,{((my \v=$_+my \n=++$+1)+n*(v%%2-v%%3))*(v%%4*n||1)}.../645/

```

Try it online!

REALLY had to work to get my byte count below those of the other non-golf-language solutions.

# Answer
> 1 votes
# Stax, 27 bytes

```
üµu█QZN/┴¶▬▲▌∙.h├û:╬πa⌠ú-Bq

```

Run and debug it

Can be improved, definitely, just can't find a way to remove the register usage.

## Explanation

```
1AJDQ_^Y+X"+-*"{]xi^^%{ysl}{d}?F
1                                 push 1
 AJ                               push 10 squared
   D                              repeat the rest of the program 100 times
    Q                             print the current number
     _^                           iteration number
       Y                          store in Y
        +X                        add the two, store in X
          "+-*"{               F  for each of +,-,*
                ]                 convert to string
                 xi^^%            x modulo (iteration count + 2)
                      {   }   ?   if true:
                       ysl        push y and apply the operation
                           { }    else:
                            d     delete the operation

```

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


# Question
Title: Check if a server is online or not for you?
Inspired from Is this site down or is it just me?

# Challenge

You have to print if a website server is online or not, for you.

# Input

The domain name, like `codegolf.stackexchange.com`

# Output

* 1/True if online
* 0/False if offline

# Rules

* Any kind of web access is allowed
* URL shorteners allowed
* Except 2 no. Rule, all standard loopholes forbidden
* You cannot use a language which cannot access internet
* This is , so shortest answer wins

Cheers!

# Answer
# APL (Dyalog Unicode), 15 bytes (SBCS)

Full program. Prompts for URL from stdin.

```
1≠≢⎕SH'ping ',⍞

```

Try it online!

prompt for URL

`'ping ',` prepend command

`⎕SH`**sh**ell out

count the number of lines in the response (will be 1 on fail, more on success)

`1≠` does 1 differ from that? (1 or 0)
> 3 votes

# Answer
# PowerShell, 21 26 bytes

+5 bytes thanks to Joel Coehoorn, who correctly pointed out that I misunderstood the challenge.

```
!!((ping @args)-match's=')

```
> 3 votes

# Answer
# Powershell, ~~32~~ 25 bytes

```
!!(resolve-dnsname @args)

```

Equal byte alternative (Will take 4 seconds, to send 4 pings):

```
!!(test-connection @args)

```

-7 bytes thx to @ZaelinGoodman
> 2 votes

# Answer
# MATL, 4 bytes

This answer takes the challenge literally and ensures that an HTTP web server is successfully running at the address.

```
4#Xi

```

The online MATL compilers do not have access to arbitrary URLs, but this can be run using MATL locally.

**Explanation**

```
     % Implicitly retrieve the input URL
4#   % Specify that we want only the second output of the next function call
Xi   % Call urlread function which attempts to make an HTTP request to the URL.
     % The second output value that we save indicates success (1) or failure (0).

```
> 2 votes

# Answer
# Bash, 10 bytes

```
curl -f $1

```

(Can't) try it online!

Works fine on my laptop. Returns `0` (linux truthy) if all is well or some other int if not (linux falsey).

From `man curl`:

> -f, --fail (HTTP) Fail silently (no output at all) on server errors. This is mostly done to better enable scripts etc to better deal with failed attempts.
> 2 votes

# Answer
# PowerShell, 13 bytes

```
!!(iwr @args)

```

There's also this, at 30 bytes:

```
(iwr @args).StatusCode -eq 200

```

Which isn't as short as some other answers, but IMO so far it's the only one that actually meets the goal of validating the web server. Others could be getting an HTTP 500-series response and saying everything is fine.

Powershell 7 also has `-SkipHttpErrorCheck`, so we can avoid some exceptions and show a nice `False` more often, but that almost doubles the size.
> 2 votes

# Answer
Using only built-in libs.

# Python 3, 77 bytes

```
from urllib.request import*
try:print(bool(urlopen(input())))
except:print(0)

```

Try it online!

-42 bytes by @Makonede!
> 2 votes

# Answer
# PHP (-F), 34 bytes

```
<?=$argn!=gethostbyname($argn)?:0;

```

(Cannot) Try it online!

Will display `1` or `0`. Reminds me a recent answer.. don't know why..

Explanation: `gethostbyname` returns the domain string when it fails, and when the first alternative `b` is missing in ternary `a?b:c`, `a`'s value is used. Truthy values are displayed `1` by default

Such kind of requests are disabled on TIO though.
> 1 votes

# Answer
# Python 2, ~~80~~ 66 bytes

```
 try:get(x).ok
 except:print 1
 else:print 0
from requests import*

```

Try it online!

-14 bytes for @Suever!
> 1 votes

# Answer
# SlimSharp, 56 bytes

```
P((new System.Net.WebClient.DownloadData(R())).L() > 0);

```

Can't test this on .Net Fiddle because it guts the `WebClient` type.
> 1 votes

# Answer
# Windows Batch, 38 bytes

```
@ping %1 >nul&&(echo 1&exit /b)&echo 0

```
> 0 votes

---
Tags: code-golf, internet
---


# Question
Title: Crazy Librarian's Arithmetic Sequence of Primes
Well, the librarian caught you cheating at your job by using your sorting algorithm, so now you're being punished. You've been ordered to create some code so the librarian can impress the object of their unrequited affection, the math teacher. So *that's* what "Other duties as assigned" means ...

Everyone is familiar with the natural number sequence in base 10, called \\$\mathbb N\\$:

> 0, 1, 2, 3, 4, 5, 6, ...

From that, we can generate the prime number sequence, let's call it \\$\mathbb P\\$, such that every element in \\$\mathbb P\\$ has exactly two divisors in \\$\mathbb N\\$, namely `1` and itself. This sequence is:

> 2, 3, 5, 7, 11, 13, ...

OK, pretty routine so far.

The librarian thought of a nifty function \\$F(x, y)\\$ that takes a number \\$x\\$ from \\$\mathbb N\\$, with the condition \\$0 \le x \le 9\\$, and a number \\$y\\$ from \\$\mathbb N\\$, and inserts \\$x\\$ into \\$y\\$'s decimal expansion in every position (i.e., prepending, inserting, or appending \\$x\\$ into \\$y\\$), then returns the sorted set of new numbers.

For example, \\$F(6, 127)\\$ would result in

> 1267, 1276, 1627, 6127

That's still kinda boring, though. The librarian wants to spice things up a bit *more* by instead specifying a new function \\$z \to \\{p : p \in \mathbb P , F(z,p) \subset \mathbb P\\}\\$, sorted ascending.

For example, \\$z(7)\\$ would be

> 3, 19, 97, 433, 487, 541, ...

because \\$37\\$ and \\$73\\$ are both prime, \\$719\\$, \\$179\\$ and \\$197\\$ are all prime, etc.

Note that \\$z(2)\\$ is empty, because no prime that has a \\$2\\$ appended will ever still be prime. Similarly for \\$\\{0,4,5,6,8\\}\\$.

Your task is to write code that will generate and output the first 100 numbers in sequence \\$z(x)\\$ for a given \\$x\\$.

## Input

A single integer \\$x\\$ such that \\$0 \le x \le 9\\$. Input can be via function argument, STDIN, or equivalent.

## Output

A sequence of the first 100 numbers, delimited by your choosing, to STDOUT or equivalent, such that the sequence satisfies \\$z(x)\\$ as described above. If \\$z(x)\\$ is empty, as is the case for \\$\\{0,2,4,5,6,8\\}\\$, the words `Empty Set` should be output instead.

## Restrictions

* This is code-golf, since you'll need to transcribe this to an index card so the librarian can show the math teacher, and your hand cramps easily.
* Standard loophole restrictions apply. The librarian doesn't tolerate cheaters.

### Reference sequences

x=1 : A069246
x=3 : A215419
x=7 : A215420
x=9 : A215421

Related: Find the largest fragile prime / Find the smallest prime from a substring / Find largest prime which is still a prime after digit deletion

# Answer
# Pyth, 49 bytes

Like the Python3 and other Pyth answer, the runtime for finding 100 numbers is prohibitive. (test suite gives 10)

```
?}z"1379".f&!tPZ!|FmtPvjzc`Z]dhl`Z*TT3"Empty Set"

```

Try it online
> 5 votes

# Answer
# Python 3, 188 bytes

```
x=input()
k=1
i=100
if x in"024568":i=print("Empty Set")
while i:k+=1;s=str(k);i-=all(sum(p%d<1for d in range(2,p))<4for p in[k*int(s[:j]+x+s[j:])for j in range(len(s)+1)])and not print(k)

```

Badly golfed, but here's something for now. Instead of checking `p in P and F(z,p) subset of P`, we check that `p*f` is a semiprime for each `f in F(z,p)`. Combine that with trial division for primality testing, and you get an `O(scary)` algorithm.
> 4 votes

# Answer
# Perl, 124 bytes

```
$p=prime_iterator;y/1379//or$i=+~print'Empty Set'}while($i<100){$_=&$p;is_prime"$`@F$'"or redo while//g;$i++

```

Requires the following command line option: `-palMntheory=:all`, counted as 16. Input taken from stdin.

Uses @DanaJ's `Math::Prime::Util` module for perl (loaded with the pragma `ntheory`). Get it with:

```
cpan install Math::Prime::Util
cpan install Math::Prime::Util::GMP

```

`is_prime` is deterministic for all values less than *264*, which is sufficient for our purposes.

---

**Sample Usage**

```
$ echo 2|perl -palMntheory=:all oscary.pl
Empty Set

$ echo 7|perl -palMntheory=:all oscary.pl
3
19
97
433
487
541
691
757
853
1471
.
.
.
718705783
720574573
737773357
745157779
747215167
767717017
768743377
770294977
771778477
774577777

```

---

**Expected Runtimes**

*x = 1* : 1m 09.2s
*x = 3* : 0m 04.2s
*x = 7* : 2m 52.5s
*x = 9* : 0m 11.5s
> 3 votes

# Answer
# Jelly, 37 bytes

```
D-ṭJœṖ€$j€Ṗ€ḌẒȦ
1Ẓ×çɗȷ2#µ“¬ḟ¦⁻v»ẇ?⁽¢°

```

Try it online! (takes the first 10 instead of 100)

## How it works

```
D-ṭJœṖ€$j€Ṗ€ḌẒȦ - Helper link. Takes n on the left and d on the right
D               - Digits of n
 -ṭ             - Append -1; Call this D
       $        - To the digits:
   J            -   Indices; Yield [1, 2, ..., len(D)]
      €         -   Over each index i:
    œṖ          -     Partition D at the index i
        j€      - Join each with d
          Ṗ€    - Remove the -1s
            Ḍ   - Convert back to integers
             Ẓ  - Is prime?
              Ȧ - True for all?

1Ẓ×çɗȷ2#µ“¬ḟ¦⁻v»ẇ?⁽¢° - Main link. Takes a digit d on the left
                 ?    - If statement:
                ẇ ⁽¢° -   Condition: d is one of 1,3,7,9?
        µ             -   Then:
    ɗ                 -     Define a dyad f(n, d):
 Ẓ                    -       n is prime?
  ×                   -       and
   ç                  -       the helper link is true
1    ȷ2#              -     Count up k = 1, 2, ... and return the first 100 k for
                             which f(k, d) is true
         “¬ḟ¦⁻v»      -   Else: Return "Empty Set"

```
> 3 votes

# Answer
# Pyth, 58

```
L}bPb|*"Empty Set"}Qj204568T.f&yZ.Amyi++<JjZTdQ>JdThl`Z100

```

This test suite only calculates the first 10 numbers because it takes far too long to generate the rest. Brute forces both primality and the inserting of the digits. Demonstrates such bad performance that I haven't been able to run it up to 100, so please tell me if there are problems.
> 1 votes

---
Tags: code-golf, math, sequence, primes, number-theory
---


# Question
Title: Crazy Librarian's Interesting Prime Permutation Index Number Generator
You saved the day with your prime sequence code, and the math teacher loved it. So much so that a new challenge was posed to the librarian (a/k/a, your boss). Congratulations, you get to code the solution so the librarian can once again impress the math teacher.

Start with the sequence of natural numbers in base-10, \\$\mathbb N\\$

> 0, 1, 2, 3, 4, 5, 6 ...

Excluding `0` and `1`, every number in this sequence either is prime, \\$\mathbb P\\$

> 2, 3, 5, 7, 11, 13 ...

or composite, \\$\mathbf C\\$

> 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20 ...

Reflecting on how the librarian thought to insert an integer digit into the decimal expansion of a number from \\$\mathbb P\\$, the math teacher instead created a function \\$G(x,y)\\$ that takes a number \\$x\\$ from \\$\mathbb N\\$ with \\$1 \le x \le 9\\$ and a number \\$y\\$ from \\$\mathbf C\\$ and inserts \\$x\\$ into the decimal expansion of \\$y\\$ in every position, in order left-to-right, selecting only unique numbers.

For example, \\$G(3,14)\\$ is \\$314, 134, 143\\$. However, \\$G(1,14)\\$ is only \\$114, 141\\$, as whether you prepend or insert the \\$1\\$ into \\$14\\$, the same number \\$114\\$ is generated.

The math teacher wondered how many times you'd have to do these permutations before you get a number that's in \\$\mathbb P\\$, if you took \\$x\\$ in increasing order. The math teacher called this the **Composite-Prime Index** of a number, and wrote it as \\$\text{CPI}(y)\\$.

For example, \\$4\\$ only needs to be done twice: \\$14, 41\\$, since \\$41\\$ is prime, so \\$\text{CPI}(4)\\$ is \\$2\\$. However, \\$8\\$ needs to be done 6 times, \\$18, 81, 28, 82, 38, 83\\$ before reaching \\$83\\$ as a prime number, so \\$\text{CPI}(8)\\$ is \\$6\\$.

Your task is to write code that will output this **Composite-Prime Index**, given an input number.

## Input

* A single integer \\$y\\$, such that \\$y\\$ is in \\$\mathbf C\\$, input via function argument, STDIN, or equivalent.
* For the purposes of calculation, you can assume \\$y\\$ will fit in usual integer ranges (e.g., assume \\$2^{31}-1\\$ as an upper bound).
* Behavior for \\$y\\$ not in *C* is undefined.

## Output

The resultant **Composite-Prime Index**, calculated as described above, output to STDOUT or equivalent, with two exceptions:

* If the *very last* permutation (i.e., appending \\$9\\$ to \\$y\\$) is the one that results in a prime, output `-1`. An example, expanded below, is \\$y=14\\$.
* If there is no permutation (i.e., \\$G(x,y)\\$ is a subset of \\$\mathbf C\\$ for all \\$1 \le x \le 9\\$), output `0`. An example, expanded below, is \\$y=20\\$.

## Examples

```
 y -> operations             : output
 4 -> 14, 41                 : 2
 6 -> 16, 61                 : 2
 8 -> 18, 81, 28, 82, 38, 83 : 6
 9 -> 19                     : 1
10 -> 110, 101               : 2
12 -> 112, 121, 212, 122, 312, 132, 123, 412, 142, 124, 512, 152, 125, 612, 162, 126, 712, 172, 127 : 19
14 -> 114, 141, 214, 124, 142, 314, 134, 143, 414, 144, 514, 154, 145, 614, 164, 146, 714, 174, 147, 814, 184, 148, 914, 194, 149 : -1
15 -> 115, 151               : 2
16 -> 116, 161, 216, 126, 162, 316, 136, 163 : 8
18 -> 118, 181               : 2
20 -> 120, 210, 201, 220, 202, 320, 230, 203, 420, 240, 204, 520, 250, 205, 620, 260, 206, 720, 270, 207, 820, 280, 208, 920, 290, 209 : 0

```

## Restrictions

* This is code-golf, since you'll need to transcribe this to an index card so the librarian can show the math teacher, and your hand cramps easily.
* Standard loophole restrictions apply. The librarian doesn't tolerate cheaters.

## Leaderboard

```
var QUESTION_ID=63191,OVERRIDE_USER=42963;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+(?:[.]\d+)?)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
> 1 votes
# Pyth, 35 bytes

```
&sKm}dPdsm{msj`dcz]khlzS9|%hxK1lK_1

```

Test suite

# Answer
> 2 votes
## Haskell, ~~166~~ 161 bytes

```
p n=mod(product[1..n-1]^2)n>0
q=p.read
n#c=[h++c:t|i<-[0..length n],(h,t)<-[splitAt i n]]
[y]%i|q y= -1|1<2=0
(y:z)%i|q y=i|1<2=z%(i+1)
f n=((n#)=<<['1'..'9'])%1

```

Usage examples: `f "8"` -\> `6`, `f "14"`-\> `-1`, `f "20"`-\> `0`.

How it works: `p` is the primality test (stolen from @Mauris' answer in a different challenge). `q` a wrapper for `p` to convert types from strings to integer. `n # c` inserts `c` at every position in `n`. `%` takes a list of numbers and an index `i`. When the first element of the list is prime, return `i`, else recure with the tail of the list and `i+1`. Stop when there's a single element left and return `-1` if it's prime and `0` otherwise.

# Answer
> 1 votes
## Minkolang 0.11, 85 bytes

```
n1(l*$d`)d9[i3G(0c2c$%$r2c*l*2c3c1+*++2gl:d2G)2gx1c2G3gx]r3XS(2M4&I)N.ikI1-4&1~N.1+N.

```

Try it here.

### Explanation (coming soon)

```
n            Take integer from input (say, n)
1(           Calculate smallest power of 10 greater than n (say, a)
  l*         Multiply by 10
    $d`      Duplicate stack and push n>a
       )     Close while loop (ends when n<=a)
        d    Duplicates a (let's call it b)

9[                                                 For loop that runs 9 times
  i1+                                              Loop counter + 1 (say, i)
     3G                                            Puts the loop counter in position 3
       (                                           Opens while loop
        0c2c$%                                     Copies n and b and pushes n//b, n%b
              $r                                   Swaps top two elements of stack
                2c*l*                              Copies b and multiplies by 10
                     2c3c*                         Copies b and i and multiplies them
                          ++                       Adds it all together (inserts i)
                            2gl:                   Gets b and divides by 10
                                d2G                Duplicates and puts one copy back
                                   )               Closes while loop (breaks when b=0)
                                    2gx            Gets and dumps b
                                       1c2G        Copies a and puts it in b's place
                                           3gx     Get and dumps i
                                              ]    Close for loop

r       Reverses stack
 3X     Dumps the top three elements (namely, n, a, and b)
   S    Removes duplicates

(                           Opens while loop
 2M                         Pushes 1 if top of stack is prime, 0 otherwise
   4&                       Jump four spaces if prime
     I)N.                   If the loop actually finishes, then all were composite,
                             so output 0 and stop.
         ik                 Pushes loop counter and breaks
           I1-              Pushes length of stack minus 1 (0 if last one was prime)
              4&1~N.        If this is 0, pushes -1, outputs as integer, and stops.
                    1+N.    Adds 1, outputs as integer, and stops.

```

# Answer
> 1 votes
# Javascript, 324 bytes

```
y=>(p=(n,c)=>n%c!=0?c>=n-1?1:p(n,++c):0,u=a=>a.filter((c,i)=>a.indexOf(c)==i),g=(x,y)=>u(((x,y,z)=>z.map((c,i)=>z.slice(0,i).join("")+x+z.slice(i).join("")).concat(y+x))(x,y,y.split(''))),h=(x,y)=>g(x,y).concat(x==9?[]:h(++x,y)),i=h(1,y).reduce((r,c,i)=>r?r:p(c,2)?i+1:0,0),console.log(p(y,2)||y<2?'':i==h(1,y).length?-1:i))

```

If y not in C, then STDOUT output is empty.

## Explanation

```
y=>(
    //Prime Test function
    p=(n,c)=>n%c!=0?c>=n-1?1:p(n,++c):0,

    //Unique function
    u=a=>a.filter((c,i)=>a.indexOf(c)==i),

    //Generates numbers from a couple x and y
    g=(x,y)=>u(((x,y,z)=>z.map((c,i)=>z.slice(0,i).join("")+x+z.slice(i).join("")).concat(y+x))(x,y,y.split(''))),

    //Generates all possible numbers from y using recusion
    h=(x,y)=>g(x,y).concat(x==9?[]:h(++x,y)),

    //Check if any prime in the generated numbers
    i=h(1,y).reduce((r,c,i)=>r?r:p(c,2)?i+1:0,0),

    console.log(
        //Is Y in C ?
        p(y,2)||y<2?
            ''
            :
            // Check if the answer is not the last one
            i==h(1,y).length?-1:i)
    )

```

# Answer
> 1 votes
# Jelly, 25 bytes

```
D-ṭJœṖ€$jþ9ẎṖ€ḌQẒµL,-yi1$

```

Try it online!

+6 bytes to allow for:

> If the very last permutation (i.e., appending 9 to y) is the one that results in a prime, output -1

## How it works

```
D-ṭJœṖ€$jþ9ẎṖ€ḌQẒµL,-yi1$ - Main link. Takes n on the left
D                         - Digits of n
 -ṭ                       - Append -1; Call this D
       $                  - To D:
   J                      -   Indices; Yield [1, 2, ..., len(D)]
      €                   -   For each index i:
    œṖ                    -     Partition D at index i
          9               - Generate the range [1,2,3,4,5,6,7,8,9]
         þ                - Pair up all pairs from the range and the partitions:
        j                 -   Join each partition with the corresponding integer
           Ẏ              - Tighten into a list of lists
            Ṗ€            - Remove the -1 from each
              Ḍ           - Convert back to integers
               Q          - Deduplicate
                Ẓ         - Replace primes with 1 and composites with 0
                 µ        - Call this list of bits B
                  L       - Length of B
                   ,-     - Pair with -1
                        $ - To B:
                      i1  -   Yield the first index of 1, or 0 if not found
                     y    - If the index is equal to the length, replace with -1

```

---
Tags: code-golf, math, sequence, primes, number-theory
---


title: What's my IP Address?

text:
# Question
Title: What's my IP Address?
I'm surprised this hasn't come up in a challenge yet.

Output the IP address of the machine you're running on. You are required to output both the local and external IP addresses.

Local IP address, ie along the default format of 192.168.x.x

Public IP address can be verified by using google https://www.google.co.uk/search?source=hp&q=whats+my+ip

Output can be in any format. IPv4 or IPv6 or any mix of each is allowed, however they must be the only output. Code can be a full program or a function.

rules apply so shortest code wins.

Standard Loopholes are forbidden.

**EDIT:** As per @Peter Taylor's comment, in the case where multiple of either type of address are present, you can choose to either output the first one, or as many as you can access. So long as at least one local and one public are present.

# Answer
# Bash + curl \+ iproute2, ~~54 50 49 48~~ 33 bytes

```
ip r g 1|awk '$0=$7'
curl eth0.me

```

Thanks @DomHastings for golfing off 1 byte!

Thanks @Sisyphus for coming up with a shorter URL!

Thanks @zeppelin for golfing off 9 bytes!
> 18 votes

# Answer
# Bash 37 31 27 bytes

This is inspired by the answer by Bruce Forte. That answer only works with IPv4 which means it doesn't work for me. I have rewritten it into a version that (only) works with IPv6:

```
ip r g b::|awk '$0=$9" "$9'

```

This is tested on Ubuntu 14.04.5 connected through PPPoE and since IPv6 is designed to be used without any NAT it will output the same IP address twice.

-6 bytes thanks to zeppelin, -2 bytes thanks to Ferrybig, -2 bytes thanks to Markasoftware.
> 9 votes

# Answer
# AutoIt, ~~56~~ 53 bytes

```
#include<Inet.au3>
ConsoleWrite(@IPAddress1&_GetIP())

```

`@IPAddress1` is a macro that returns

> IP address of first network adapter

`_GetIP()` returns

> the public IP address.

---

-3 bytes thanks to @mınxomaτ
> 7 votes

# Answer
# Mathematica, 17 bytes

~~Mathematica has a builtin for everything~~

```
$MachineAddresses

```

As described in the documentation, this builtin command lists all IP addresses (both local and external) associated with your device.
> 7 votes

# Answer
# C#, ~~196~~ ~~194~~ ~~188~~ 163 bytes

```
namespace System.Net.Sockets{using Linq;_=>Dns.GetHostEntry("").AddressList.First(i=>(int)i.AddressFamily==2)+" "+new WebClient().DownloadString("http://eth0.me")}

```

*Saved 2 bytes thanks to @Xynos.*
*Saved 25 bytes thanks to @Nick.*

Full/Formatted Version:

```
namespace System.Net.Sockets
{
    using Linq;

    class P
    {
        static void Main()
        {
            Func<object, string> f = _ =>
                Dns.GetHostEntry(Dns.GetHostName())
                    .AddressList
                    .First(i => (int)i.AddressFamily == 2) + " " + new WebClient().DownloadString("http://eth0.me");

            Console.WriteLine(f(null));

            Console.ReadLine();
        }
    }
}

```
> 6 votes

# Answer
## PowerShell v4+, 40 36 bytes

```
NetIPAddress|% IPA*
iwr eth0.me|% C*

```

*(Only works on Server 2012 R2 or above, or Windows 8.1 or above. Doesn't work on TIO.)*

Does exactly what it says on the tin. Gets the local network IP addresses and selects just the `IPA`ddress portion thereof (e.g., filters out the subnet mask, the gateway, etc.).

The second is a `Invoke-WebRequest` to `http://eth0.me` which simply gets the `C`ontent thereof; i.e., just the public IP address.

---

Ungolfed version:

```
(Get-NetIPAddress).IPAddress
(Invoke-WebRequest eth0.me).content

```
> 6 votes

# Answer
#Unix Shell + stunclient, 40 bytes

```
stunclient stun.vo.lu|cut -d: -f2|sed 1d

```

Makes use of a STUN protocol:

> Session Traversal Utilities for NAT (STUN) is a protocol that serves as a tool for other protocols in dealing with Network Address Translator (NAT) traversal. It can be used by an endpoint to determine the IP address and port allocated to it by a NAT

The STUN server name is from the Public STUN server list.

The output format is:

```
 LOCAL IPV4 ADDRESS
 PUBLIC IPV4 ADDRESS

```

Note that both lines will be indented with a single space, but I believe this does not break the output rules as written.

Sample output:

```
  192.168.1.100
  209.85.233.147

```
> 4 votes

# Answer
# curl (bash one-liner): 27 bytes

```
curl -w%{local_ip} eth0.me

```

The result is printed on `stdout` and looks like this:

```
1.2.3.4
192.168.0.10
# no trailing newline, use "curl -w%{local_ip}\\n eth0.me" for it

```

`curl` should be at least of version 7.29.0 (from Feb 6, 2013).

The answer is based on https://codegolf.stackexchange.com/a/139538/66016.
> 4 votes

# Answer
## Go, MacOS only, 10 bytes

In macOS this killswitch could be used, it can print current private active IP and public IP:

```
$ killswitch
Interface  MAC address         IP
en1        bc:34:36:d2:81:ba   192.168.2.10

Public IP address: 179.43.176.99

No VPN interface found, verify VPN is connected

```

This is not a built-in tool but tries to simplify the process of finding the proper IP's.

The output could get by using commands like:

```
$ route get 0.0.0.0

$ ifconfig | pcregrep -M -o '^[^\t:]+:([^\n]|\n\t)*status: active'

$ networksetup -listnetworkserviceorder

$ scutil --dns

```

Public IP:

```
$ dig o-o.myaddr.l.google.com @ns.google.com txt +short

```
> 4 votes

# Answer
**Python 3, 124 133 bytes**

```
from urllib2 import urlopen
import socket
a=urlopen('http://eth0.me').read()
b=socket.gethostbyname(socket.gethostname())
print a,b

```
> 3 votes

# Answer
**PowerShell v3+ (alternative answer for windows 7+)**

```
((ipconfig) -match "v4").split(":")[1]
Invoke-RestMethod eth0.me

```
> 3 votes

# Answer
# Bash + Awk + Curl, 43 bytes

using only built in tools for Mac and Linux

```
ifconfig|awk '/bro/{print $2}';curl eth0.me

```
> 3 votes

# Answer
## Node.js (JavaScript) ~~224~~ ~~223~~ ~~194~~ ~~175~~ ~~173~~ 130 bytes

```
r=require,l=console.log,r('dns').lookup(r('os').hostname(),(a,b)=>l(b));r('http').get('http://eth0.me',a=>a.on('data',c=>l(c+"")))

```

Ungolfed version:

```
require('dns').lookup(require('os').hostname(), (err, loc, fam) => console.log(loc));
require('http').get('http://eth0.me', res => {
    res.on('data', chunk => console.log(chunk + ""));
});

```

---

* *Saved 1 byte* (due to unnecessary semicolon).
* *Saved 29 bytes thanks to @AndrewLi* (used arrow functions for shorter code).
* *Saved 19 bytes thanks to @MiniGod* (used `.get()` instead of `.request()` \- `.end();` removed).
* *Saved 2 bytes thanks to @Zacharý* (parentheses not needed around a lone parameter of an arrow function).
* *Saved 43 bytes thanks to @Birjolaxew* (stored `require` and `console.log` in single-letter variables, passed url directly to `require('http').get`, logged output directly from `data` event).
> 2 votes

# Answer
**Python 2.7.13 128 bytes**

```
print __import__("urllib").urlopen("http://eth0.me").read(),__import__("socket").gethostbyname(__import__("socket").getfqdn())

```
> 2 votes

# Answer
## R, ~~142~~, ~~140~~, 137 bytes

```
library(magrittr);system("ipconfig",int=T)%>%regmatches(.,regexpr("v4.+",.))%>%{a=nchar(.);substr(.,a-14,a)};readLines("http://eth0.me")

```

Tested on win10 and R (3.4.1).
Thanks for @Bruce-Forte for short URL.

Ungolfed version:

```
library(magrittr)
system("ipconfig",int=T) %>%
     regmatches(.,regexpr("v4.+",.)) %>%
      {a <- nchar(.)
       substr(., a - 14, a)}
readLines("http://eth0.me")

```
> 1 votes

# Answer
# Windows' Batch File, 116 bytes

```
@for /f "tokens=1-2 delims=:" %%a in ('ipconfig^|find "v4"')do @echo%%b
@powershell -Command "(iwr eth0.me).content"

```

The first line iterates through the results of running `ipconfig` and gets your local IPv4 address.

For the public IP part, I had to steal a bit from the marvelous Powershell answer because, as far as I know, there is no way to get the machine's public IP using solely batch scripting.

We start with an `@` sign, to suppress echoing the prompt (`C:\...\path>`), then run the Powershell command `Invoke-WebRequest` (with its alias, `iwr`) and extract the `content` part of that.

I experimented with *not* using `(...).content` and, instead, only running the command and extracting the actual information from the complete output, using batch. But that proved to be way longer than this solution, so I kept it.

Tested on Windows 10.0.15063.
> 1 votes

# Answer
# Bash + Curl, 24 bytes

```
hostname -i;curl eth0.me

```
> 1 votes

# Answer
# MS-SQL, 59 bytes

```
SELECT TOP 1 local_net_address
FROM sys.dm_exec_connections

```

Returns the client-facing IP address of the SQL instance executing the query.
> 1 votes

# Answer
# VBA, 58 Bytes

***Whoops, does not handle local address - fix in progress***

> ***Note:*** Uses reference to
>
> `Microsoft Internet Controls`

Anonymous VBE immediate window function that takes no input and outputs the user's IP address via an Internet Explorer window

```
Set i=New InternetExplorer:i.Visible=1:i.Navigate"eth0.me"

```
> 1 votes

# Answer
# Bash — 29 bytes (linux)

```
curl ipinfo.io/ip
hostname -i

```
> 1 votes

# Answer
# Python 3, 97 bytes

```
from socket import*
from requests import*
gethostbyname(gethostname()),get('http://eth0.me').text

```

returns tuple with `('LOCAL_IP', 'PUBLIC_IP')`, as apparently

```
x = 2,3
type(x)
>>> tuple

```

# Python 3, 103 bytes

```
from socket import*
from requests import*
gethostbyname(gethostname()),get('http://api.ipify.org').text

```

ditto, read below.

---

# Python 3, 107 bytes

First solution

```
from socket import*
from requests import*
gethostbyname(gethostname())+" "+get('http://api.ipify.org').text

```

The `+" "+` part is for joining strings together.

If you leave just the `+` sign, 103 bytes are possible, but would yield the strings without spaces which could lead to results like this `"5.5.5.111222.222.222.222"` and they should still be readable, as there are only 3 digits at max in every ip part.

But there are edge cases like `"5.5.5.11111.222.222.222"` where it would be impossible to distinguish the local vs public part.

Other possible savings are in the public ip grabber tool. I used this site, as it was the first thing I found on the Internet and it returns html with just text in it, which is super nice. I saw other people using `http://eth0.me`, but it doesn't load for me on my machine and my antivirus has it blacklisted, thus Python raises a `ConnectionError`. It loads through Tor though, so I don't know whether I should use it.

# Python 3, 101 bytes

```
from socket import*
from requests import*
gethostbyname(gethostname())+" "+get('http://eth0.me').text

```
> 0 votes

---
Tags: code-golf, internet
---


title: Get the IP address of google.com

text:
# Question
Title: Get the IP address of google.com
# Challenge

In this simple challenge, you have to print the public IP address of `google.com`.

# Rules

* You have to output either the IPv6 or IPv4 address, and do it by somehow using internet.
* Output does not strictly need to be the IP address, your answer will be valid if the correct IP address is somewhere in the output, like `Hello - google.com - 142.250.67.78` is a valid output.
* You can use DNS queries and any kind of web APIs or web scraping.
* Standard loopholes apply, except usage of URL shorteners, wanna see how creative you can get ;-)
* This is , so the shortest answer wins!!

# Answer
# Zsh, 40 bytes

```
echo {0..255}.{0..255}.{0..255}.{0..255}

```

Try it online!

Since the output only needs to *contain* the IP address, we can just enumerate all of them! This probably isn't the shortest option, but it's funny!
> 13 votes

# Answer
## Windows Batch, 15 bytes

```
ping google.com

```

### Example run

```
C:\>ping google.com

Pinging google.com [8.7.198.46] with 32 bytes of data:
Request timed out.
Request timed out.
Request timed out.
Request timed out.

Ping statistics for 8.7.198.46:
    Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),

```
> 7 votes

# Answer
# Bash, 14 bytes

Requires `dnsutils`.

```
dig google.com

```
> 6 votes

# Answer
# Java 8, 47 bytes

```
v->java.net.InetAddress.getByName("google.com")

```

(Don't) try it online (local run outputs `google.com/142.250.179.206`).

**Explanation:**

```
v->                          // Method with empty unused parameter & InetAddress return
  java.net.InetAddress       //  Create and return an InetAddress-instance
    .getByName("google.com") //  for hostname "google.com"

```

When this `InetAddress`-instance is printed, it will use its `InetAddress.html#toString()` method by default, which prints in the format `hostname / literal IP address`.
> 5 votes

# Answer
# Powershell 5, 26 bytes

```
resolve-dnsname google.com

```

luckily, powershell has a CMDlet for this!

Somehow this does not work on TIO, but on powershell 5

```
Name                                           Type   TTL   Section    IPAddress
----                                           ----   ---   -------    ---------
google.com                                     AAAA   149   Answer     2404:6800:4007:805::200e
google.com                                     A      273   Answer     142.250.67.78

```
> 3 votes

# Answer
# Ruby, 41 bytes

```
require'resolv';Resolv.getaddress'goo.gl'

```

Try it online!

Or as an alternative:

`dig goo.gl`

`wget goo.gl`
> 3 votes

# Answer
# C (gcc) (`-m32`), 67 bytes

To avoid having to include any header files, I flatten the structure and manually dereference the first entry of the `h_addr_list` member of the `hostent` structure. Replace `google.com` with `localhost` to test in tio.run.

```
f(){puts(inet_ntoa(**(((int***)gethostbyname("google.com"))[4])));}

```

Try it online!
> 3 votes

# Answer
# Bash + dnsutils, 15 bytes

```
host google.com

```
> 2 votes

# Answer
# PHP, 20 bytes

```
<?=`ping google.co`;

```

For some reason `google.co` returns exactly the same IP as `google.com`.
> 2 votes

# Answer
# MATLAB/Octave, 26 bytes

```
resolvehost goo.gl address

```

This solution uses `resolvehost` which is part of the Instrumentation Toolbox (`instrument-control` in Octave). We provide a second input (`'address'`) to specify that we want the IP address.

Also we avoid using parentheses because both inputs should be interpreted as strings already so we can save 5 bytes by not using parentheses, quotes, and commas:

Long form: `resolvehost('goo.gl','address')`

Notes:

* On Octave at least, we cannot shorten `address` (in many MATLAB/Octave commands you can shorten string literals). I don't have MATLAB available to me with this toolbox so it's possible this could be shortened in MATLAB.
* We could alternately use the second output without a second input: `[,a]=resolvehost('goo.gl')` which would be the same length as this answer but we have to use parentheses and quotes. Also the empty first output is only valid in Octave. In MATLAB we would have to do `[~,a]=resolvehost('goo.gl')` which is 1 byte longer.
> 2 votes

# Answer
## Golang, 77 bytes

```
package main;import(."net";."fmt");func main(){Print(LookupIP("google.com"))}

```
> 2 votes

# Answer
# Mathematica, 23 Bytes

```
HostLookup["google.co"]

```

Like with most things in life, Mathematica/Wolfram Language has a builtin for it. Requires version 11 or above.
> 2 votes

# Answer
# Bash, ~~164 bytes~~ 127 bytes

```
base64 -d<<<3dYBIAABAAAAAAABBmdvb2dsZQNjb20AAAEAAQAAKRAAAAAAAAAMAAoACCjxxt05OkuU|nc 1.1.1.1 -u 53|hexdump -e '4/1 "%0.2d.""\n"'

```

Why use `dig` when you can use netcat.

Example Run:

```
221.214.129.128.
00.01.00.01.
00.00.00.01.
06.103.111.111.
103.108.101.03.
99.111.109.00.
00.01.00.01.
192.12.00.01.
00.01.00.00.
01.29.00.04.
142.250.182.238. //Google's IP
00.00.41.04.
208.00.00.00.

```

EDIT: Saved a lot of bytes thanks to @DigitalTrauma
> 2 votes

# Answer
# Python 3, ~~58~~ 54 bytes

-4 bytes by Arnauld, who got better reading skills than me...

```
from socket import*
print(gethostbyname('google.com'))

```
> 1 votes

# Answer
# Standard ML, 35 bytes

```
OS.Process.system"ping google.com";

```

I never used it before, but it turns out there is a `OS` structure in the basis library which lets you execute arbitrary commands in the system's default shell.
> 1 votes

# Answer
# Windows Batch, 19 bytes

```
nslookup google.com

```
> 0 votes

# Answer
# JavaScript (Node.js), 57 bytes

A full program that prints the first A record (IPv4).

```
require('dns').lookup('google.com',(_,s)=>console.log(s))

```

(Don't) Try it online!
> 0 votes

# Answer
# C# (Visual C# Interactive Compiler), 44 bytes

A function that prints the IP among other things

```
_=>System.Net.Dns.GetHostEntry("google.com")

```

Can't Try it online!
> 0 votes

# Answer
# Visual Basic .NET (.NET Core), ~~60~~ 53 bytes

```
Console.WriteLine(Net.Dns.GetHostEntry("google.com"))

```

Try it online!

-7 bytes thanks to @JoelCoehoorn
> 0 votes

# Answer
# PHP, 31 bytes

```
<?=gethostbyname('google.com');

```

(Cannot) Try it online!

Works on my localhost, still trying to golf it
> 0 votes

# Answer
# Perl 5, 53 bytes

```
say join".",map ord,gethostbyname("google.com")=~/./g

```

Try it offline with `perl -E'say join".",map ord,gethostbyname("google.com")=~/./g'`
> 0 votes

# Answer
# Python 3, 46—47 bytes

```
from socket import*
getaddrinfo('google.co',0)

```

TIO doesn't let me run it, but the Jupyter and normal compiler returns this:

```
[(<AddressFamily.AF_INET: 2>, 0, 0, '', ('173.194.220.100', 0)),
 (<AddressFamily.AF_INET: 2>, 0, 0, '', ('173.194.220.113', 0)),
 (<AddressFamily.AF_INET: 2>, 0, 0, '', ('173.194.220.101', 0)),
 (<AddressFamily.AF_INET: 2>, 0, 0, '', ('173.194.220.102', 0)),
 (<AddressFamily.AF_INET: 2>, 0, 0, '', ('173.194.220.139', 0)),
 (<AddressFamily.AF_INET: 2>, 0, 0, '', ('173.194.220.138', 0))]

```

While the end result leads to google.com, the .com version of this code would return entirely different ip-ranges. Which would add +1 to the byte amount if you consider this not fair.
> 0 votes

# Answer
# Shell / cURL: 12 bytes

```
curl g.co -v        # 12
curl goo.gl -v      # 14
curl google.co -v   # 17
curl google.com -v  # 18

```

IPs

```
$ nslookup google.com
Non-authoritative answer:
Name:   google.com
Address: 172.217.23.238
Name:   google.com
Address: 2a00:1450:4014:80d::200e

$ nslookup g.co
Non-authoritative answer:
Name:   g.co
Address: 172.217.23.238
Name:   g.co
Address: 2a00:1450:4014:80d::200e

```
> 0 votes

---
Tags: code-golf, internet
---