# Question
Title: A list of number modulus their indices in the list
**A simple one:** Take a list of positive integers as input and output the numbers modulus their 1-based index in the list.

If the input integers are `{a, b, c, d, e, f, g}` then the output should be `{a%1, b%2, c%3, d%4, e%5, f%6, g%7}` where `%` is the modulus operator.

---

**Test cases:**

```
10  9  8  7  6  5  4  3  2  1
 0  1  2  3  1  5  4  3  2  1

8 18  6 11 14  3 15 10  6 19 12  3  7  5  5 19 12 12 14  5
0  0  0  3  4  3  1  2  6  9  1  3  7  5  5  3 12 12 14  5

1
0

1  1
0  1

```

# Answer
> 12 votes
# Haskell, 20 bytes

```
($[1..]).zipWith mod

```

Try it online!

A trick to `flip` I learned from a golf of Anders Kaseorg.

# Answer
> 11 votes
# Operation Flashpoint scripting language, 73 bytes

```
f={l=_this;r=[];i=0;while{i<count l}do{r=r+[(l select i)%(i+1)];i=i+1};r}

```

**Call with:**

```
numList = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
hint format["%1\n%2", numList, numList call f];

```

**Output:**

# Answer
> 9 votes
# Python 2, 35 bytes

```
i=1
for x in input():print x%i;i+=1

```

Try it online!

Counts the index up manually, as per a tip of mine.

# Answer
> 8 votes
# Jelly, 2 bytes

```
%J

```

Try it online!

**Explanation:**

```
%J
 J List 1 .. len(input). This is results in a list of the indexes.
%  Modulo.

```

Basically, the code modulos the original list by the list of indexes.

# Answer
> 6 votes
# MATL, ~~4~~, 3 bytes

```
tf\

```

Try it online!

*One byte saved thanks to @LuisMendo!*

# Answer
> 6 votes
# R, 27 bytes

```
x=scan();cat(x%%1:sum(1|x))

```

saved 5 bytes thanks to @Jarko

saved 4 more thanks to @Giuseppe

saved 2 more thanks to @Taylor Scott

Saved 2 more thanks to @returnbull

# Answer
> 6 votes
# R, ~~24~~ 18 bytes

```
pryr::f(x%%seq(x))

```

Evaluates to the function:

```
function (x)
x%%seq(x)

```

Which uses `seq_along()` to create a vector of the same length as `x`, starting at 1, and then `%%` to take the modulo.

Default behaviour of `seq` when presented with a vector is `seq(along.with = x)` which is the same output as `seq_along(x)`, but 6 bytes shorter.

# Answer
> 5 votes
# 05AB1E, 2 bytes

```
ā%

```

Try it online! or Try all tests

```
ā  # Push the range(1, len(a) + 1)
 % # Mod each element in the input by the same one in this list

```

# Answer
> 5 votes
# APL (Dyalog), 5 bytes

```
⍳∘≢|⊢

```

Try it online!

the indices

of

the length of the argument

`|` that modulus

the argument

# Answer
> 5 votes
# Cubix, 19 bytes

```
;ww.1I!@s%Ow;)Sow.$

```

Try it online!

```
    ; w
    w .
1 I ! @ s % O w
; ) S o w . $ .
    . .
    . .

```

Watch It Run

A fairly straight forward implementation.

* `1` push 1 to the stack to start the index
* `I!@` get the integer input and halt if 0
* `s%Ow` swap the index up, mod, output result and change lane
* `;)` remove result and increment index
* `Sow` push 32, output space and change lane (heading down from o)
* `$O` jump the output
* `w;w` change lange, remove 32 from stack and change lane onto the `I` input

# Answer
> 4 votes
## Mathematica, 22 bytes

```
#&@@@Mod~MapIndexed~#&

```

One more Mathematica approach.

# Answer
> 4 votes
# Starry, ~~75~~ 70 bytes

```
      +`  , + +   *    +  + +      +*   +    *  .               + + .'

```

Try it online!

### Explanation

This is an infinite loop that keeps reading numbers from the input and increasing a counter initiallized at `1`. For each pair of input and counter, the modulus is computed and printed.

To end the loop when input has been exhausted, the following trick is used. When no more input is available, trying to read one more number gives a `0`. Thus, we divide the read number by itself, and if it is `0` the program ends with an error. Else we discard the result and continue.

```
      +              Push 1. This is the initial value of the counter
`                    Mark label
  ,                  Read number from input and push it. Gives 0 if no more input
 +                   Duplicate top of the stack
 +                   Duplicate top of the stack
   *                 Pop two numbers and push their division. Error if divisor is 0
    +                Pop (discard) top of the stack
  +                  Swap top two numbers
 +                   Duplicate top of the stack
      +              Push 1
*                    Pop two numbers and push their sum. This increases the counter
   +                 Rotate stack down, to move increased counter to bottom
    *                Pop two numbers and push their modulus
  .                  Pop a number and print it as a number
               +     Push 10
 +                   Duplicate top of the stack
 .                   Pop a number (10) and print it as ASCII character (newline)
'                    If top of the stack is non-zero (it is, namely 10) go to label

```

# Answer
> 3 votes
# Brachylog, 9 bytes

```
l⟦₁;?↔z%ᵐ

```

Try it online!

### Explanation

```
l⟦₁          [1, ..., length(Input)]
   ;?↔z      Zip the Input with that range
       %ᵐ    Map mod

```

# Answer
> 3 votes
# Japt `-m`, ~~5~~ ~~4~~ 3 bytes

```
uVÄ

```

Try it

-1 byte thanks to ETHproductions

# Answer
> 3 votes
# R, 22 bytes

```
pryr::f(x%%1:sum(x|1))

```

R performs 1:length(x) before doing the modulus.

# Answer
> 3 votes
# Itr, 5 bytes

`#äL¹%`

online interpreter

# Explanation

```
#     ; read the list from standard input
 äL   ; push its length
   ¹  ; converted to 1-based range
    % ; point-wise modulo
      ; implicitly output list

```

---

# Itr, 4 bytes

`#L¹%`

The `ä` before the `L` is no-longer necessary in newer versions

# Answer
> 2 votes
# Python 2, 42 bytes

```
lambda l:[v%(i+1) for i,v in enumerate(l)]

```

Try it online!

# Answer
> 2 votes
# Mathematica, 21 bytes

```
#~Mod~Range@Length@#&

```

Try it online!

or **20 bytes** (by Martin)

```
#~Mod~Range@Tr[1^#]&

```

# Answer
> 2 votes
## Haskell, 22 bytes

```
zipWith(flip mod)[1..]

```

Try it online!

Also: `flip(zipWith mod)[1..]`.

# Answer
> 2 votes
# Excel VBA, ~~59~~ 46 Bytes

### Golfed

Anonymous VBE Immediate window funtion that takes a space () delimited array string as input from range `[A1]` and output the numbers modulus their 1-based index in the starting list to the VBE immediate window

```
For Each n In Split([A1]):i=i+1:?n Mod i;:Next

```

Input / Output:

```
[A1]="10 9 8 7 6 5 4 3 2 1" ''# or manually set the value
For Each n In Split([A1]):i=i+1:?n Mod i;:Next
 0  1  2  3  1  5  4  3  2  1

```

### Old `Sub`routine version

Subroutine that takes input as a passed array and outouts to the VBE immediate window.

```
Sub m(n)
For Each a In n
i=i+1
Debug.?a Mod i;
Next
End Sub

```

Input / Ouput:

```
m Array(10,9,8,7,6,5,4,3,2,1)
 0  1  2  3  1  5  4  3  2  1

```

### Ungolfed

```
Option Private Module
Option Compare Binary
Option Explicit
Option Base 0 ''# apparently Option Base 1 does not work with ParamArrays

Public Sub modIndex(ParamArray n() As Variant)
    Dim index As Integer
    For index = LBound(n) To UBound(n)
        Debug.Print n(index) Mod (index + 1);
    Next index
End Sub

```

Input / Output:

```
Call modIndex(10,9,8,7,6,5,4,3,2,1)
 0  1  2  3  1  5  4  3  2  1

```

# Answer
> 2 votes
# Thunno 2, 2 bytes

```
ż%

```

Try it online!

#### Explanation

```
ż%  # Implicit input
 $  # Vectorised modulo
ż   # List [1..length]
    # Implicit output

```

# Answer
> 2 votes
# Rust, 46 bytes

```
|v|v.iter().zip(1..).map(|(n,i)|n%i).collect()

```

Rust Playground

# Answer
> 1 votes
# CJam, 9 bytes

```
{_,,:).%}

```

Anonymous block that expects an array on the stack and replaces it by the output array.

**Try it online!**

### Explanation

```
{       }    e# Define block
 _           e# Duplicate
  ,          e# Length
   ,         e# Range, 0-based
    :)       e# Add 1 to each entry
      .%     e# Vectorized modulus

```

# Answer
> 1 votes
# J, 9 bytes

```
>:@i.@#|[

```

1 ... n | original list

`|` is mod

# Answer
> 1 votes
# C, 52 bytes

```
i;f(n,l)int*l;{for(i=0;i++<n;)printf("%d ",*l++%i);}

```

Try it online!

# Answer
> 1 votes
# JavaScript (ES6), 22 bytes

```
a=>a.map((x,y)=>x%++y)

```

# Answer
> 1 votes
# AWK, 13

```
{print $1%NR}

```

Try it online.

# Answer
> 1 votes
# tcl, 35

```
lmap l $L {puts [expr $l%[incr i]]}

```

## demo

# Answer
> 1 votes
# GNU APL 1.2, 9 bytes

```
(⍳⍴R)|R←⎕

```

APL operates from right to left, hence the parentheses.

`R←⎕` assigns user input to vector `R`.

`⍴R` gives the length of the vector; `⍳⍴R` gives a vector with all numbers from 1 to that length (so the indices).

`|` is the mod operator (`a|b` yields `b%a`). APL operates on arrays, so the code snippet a vector containing each element from the user's input mod its index.

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

```
a->[a[n]%n|n<-[1..#a]]

```

Try it online!

# Answer
> 1 votes
# Pyth, 5

```
.e%bh

```

Online test.

```
    hk     # 1-based index of (implicit) lambda variable
   b       # element
  %        # element mod (1-based index)
.e    Q    # enumerated map over (implicit) input

```

# Answer
> 1 votes
# Octave, 19 bytes

```
@(n)mod(n,1:nnz(n))

```

Try it online!

An anonymous function that takes **n** as input, and performs element-wise modulus with the list **1, 2, 3**.

# Answer
> 1 votes
# Braingolf, 18 bytes

```
V1R&,{v.m1+v%}&,=;

```

Try it online!

## Explanation

```
V1R&,{v.m1+v%}&,=;  Implicit input from commandline args
V1R                 Create stack2, push 1 to it, and return to stack1
   &,               Reverse stack1
     {.......}      Foreach loop, runs for each item in stack1
      v             Switch to stack2
       .m           Duplicate last item on stack and move duplicate to stack1
         1+         Increment last item on stack
           v%       Return to stack1, pop last 2 items and push modulus result
              &,    Reverse stack1
                =   Output stack1
                 ;  Suppress implicit output

```

# Answer
> 1 votes
# Java 8 / C#, 39 bytes

```
a->{for(int i=0;i<a.length;a[i]%=++i);}

```

Try it here.

Also works in C# by replacing `->` with `=>` and `length` with `Length`:

```
a=>{for(int i=0;i<a.Length;a[i]%=++i);}

```

Try it here.

**Explanation:**

```
a->{                       // Method with integer-array parameter and no return-type
  for(int i=0;i<a.length;  //  Loop over the indexes of the array (0-indexed)
      a[i]%=++i            //   And replace every integer with itself mod (1+i)
  );                       //  End of loop
}                          // End of method

```

Modifies the input-array, hence the lack of a return.

# Answer
> 1 votes
# Ruby, 25 bytes

```
->x{x.map{|y|$.+=1;y%$.}}

```

Try it online!

# Answer
> 1 votes
# Swift 4, 18 bytes

```
zip(a,1...).map(%)

```

# Answer
> 1 votes
# Common Lisp, 57 bytes

```
(defun m(l &aux(i 0))(mapcar(lambda(x)(mod x(incf i)))l))

```

Try it online!

# Answer
> 1 votes
# Perl 6, 7 bytes

```
*Z%1..*

```

Test it

## Expanded:

```
*      # WhateverCode lambda (this is the parameter)
Z[%]   # zipped using infix modulus operator (&infix:«%»)
1 .. * # Range starting from 1 (doesn't stop)

```

# Answer
> 1 votes
# Arturo, 20 bytes

```
$=>[0map&=>[%&<=1+]]

```

Try it

# Answer
> 1 votes
# Thunno `D`, \\$ 6 \log\_{256}(96) \approx \\$ 4.94 bytes

```
LR1+z%

```

Attempt This Online!

#### Explanation

```
LR1+z%  # D flag duplicates input
LR      # Push range(len(input))
  1+    # Add one
    z%  # Mod the input by this
        # Implicit output

```

# Answer
> 1 votes
# Pip `-p`, 6 bytes

```
g%U,#g

```

Attempt This Online!

#### Explanation

```
g%U,#g  # Input on command line
g%      # The input list mod
   ,#g  # range(len(input))
  U     # incremented
        # Implicit output

```

# Answer
> 1 votes
# J-uby, 22 bytes

```
~:zip&(1..)|:*&(:/&:%)

```

Attempt This Online!

## Explanation

```
~:zip & (1..) | :* & (:/ & :%)

~:zip & (1..) |                 # Zip with endless range 1.., then
                :* & (       )  # Map with...
                      :/ & :%   #   Reduce with modulo

```

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

```
a=>a.map((x,y)=>x%~y)

```

Try it online!

# Answer
> 1 votes
# Desmos, 26 bytes

```
f(L)=mod(L,[1...L.length])

```

Try It On Desmos!

# Answer
> 1 votes
# Vyxal, 2 bytes

```
ż%

```

Try it Online!

```
 % # Modulo by
ż  # Range from 1 to length of input

```

# Answer
> 0 votes
# Python 3, 46 bytes

```
lambda x:[0]+[x[i]%i for i in range(1,len(x))]

```

Simples ;)

# Answer
> 0 votes
# Go, 68 bytes

Go isn't hopelessly defeated (kinda is, but nvm that) because it has that nice `range` which is the equivalent of Python's `enumerate()`.

```
func f(l[]int)(r[]int){for i,v:=range l{r=append(r,v%(i+1))};return}

```

Try it online!

# Answer
> 0 votes
# PHP, 37 bytes

```
<?foreach($_GET as$v)echo$v%++$k." ";

```

Try it online!

Output separeted by an underscore

PHP, 35 bytes

```
<?foreach($_GET as$v)echo$v%++$k,_;

```

Try it online!

# Answer
> 0 votes
# Python, 41 bytes

```
f=lambda l,i=1:l and[l[0]%i]+f(l[1:],i+1)

```

Try it online!

A recursive solution. One byte longer than using `enumerate`. Other attempts:

```
f=lambda l,i=1:l and[l.pop(0)%i]+f(l,i+1)
f=lambda l,i=0:l[i:]and[l[i]%-~i]+f(l,i+1)
f=lambda l:l and f(l[:-1])+[l[-1]%len(l)]

```

The last one really wants to use `pop` but the order of evaluation is wrong.

# Answer
> 0 votes
# Perl 6, 18 bytes

```
{map (*+1)R%*,.kv}

```

Accepts the list as its sole argument.

# Answer
> 0 votes
# Perl6, ~~22~~ 21 bytes

```
say $_%++$ for @*ARGS

```

And a more readable version:

```
# Store initial index state
# The "++$" in the golf version increments an anonymous state variable for this.
my $index = 0;
# Iterate over the command-line arguments
for @*ARGS -> $number {
    # Increment the current index
    $index++;
    # Print out the result for this element
    say $number % $index;
}

```

Usage:

```
perl6 whatever-you-named-it.p6 [space-separated numbers go here]

```

Note that if we don't need to actually *print* the output, we can remove the initial `say`, saving 4 bytes to bring the total down to 17.

# Answer
> 0 votes
# k, 12 bytes

```
{(1+!#x)!'x}

```

Try it online.

# Answer
> 0 votes
# Aceto, 12 bytes

```
%pLI
ILOM
ri

```

It's a bit hard to see because there's no line break after the result is printed. Input is taken one number at a time, seperated by linebreaks.

### Explanation:

Read a line and cast it to an integer:

```
ri

```

Load quick storage (initially an empty string) and increment it (autocasts to int; --\> 1)

```
IL

```

Calculate and print modulo, load quick storage again, increment and save it:

```
%pLI
   M

```

Go back to the start:

```
  O

```

### Example in- and output:

```
10
0
9
1
8
2
7
3
6
1
5
5
4
4
3
3
2
2
1
1

```

For one byte the output can look nicer:

```
%pLI
ILnM
riO

```

# Answer
> 0 votes
# Actually, 6 bytes

```
;ru@♀%

```

Try it online!

Explanation:

```
;ru@♀%
;ru     push [1, len(L)]
   @♀%  modulo of pairs from each list ([L[0]%1, L[1]%2, ...])

```

# Answer
> 0 votes
# Ruby, 40 bytes

```
->q{q.each_with_index.map{|n,i|n%(i+1)}}

```

# Answer
> 0 votes
# Clojure, 25 bytes

```
#(map mod %(rest(range)))

```

`(range)` generates an infinite sequence of integers starting from 0, `rest` drops the first, and `map`ping with multiple sequences applies the operation to corresponding elements (and stops with the shorter sequence).

# Answer
> 0 votes
# jq, 28 characters

```
to_entries[]|.value%(.key+1)

```

Sample run:

```
bash-4.4$ jq 'to_entries[]|.value%(.key+1)' <<< '[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]'
0
1
2
3
1
5
4
3
2
1

```

Try in jq‣play

For +5 characters you can enclose all the code in brackets and ask for compact output to get JSON output. But that not seems to be required.

# Answer
> 0 votes
# NewStack, 3 bytes

```
ᵢ%ṅ

```

## The breakdown:

```
ᵢ    Append user's input to the stack
 %ṅ  Mod stack by 1-based index of each element

```

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


title: The all-high powerful numbers

text:
# Question
Title: The all-high powerful numbers
We've had powerful numbers, yes, but what about *highly* powerful numbers?

### Highly powerful numbers

Let \\$n\\$ be a positive integer in the form

$$n = p\_1^{e\_{p\_1}(n)}p\_2^{e\_{p\_2}(n)}\cdots p\_k^{e\_{p\_k}(n)}$$

for distinct, increasing primes \\$p\_1, p\_2, ..., p\_k\\$ and, where \\$e\_{p\_i}(n)\\$ is a positive integer for all \\$i = 1, 2, ..., k\\$. Note that we don't include zero exponents here.

Now, for such an \\$n\\$, define

$$\operatorname{prodexp}(n) = \begin{cases} 1, & n = 1 \\ \prod^k\_{i=1} e\_{p\_i}(n), & n \> 1\end{cases}$$

Such an \\$n\\$ is said to be *highly powerful* if, for all \\$1 \le m \< n\\$, \\$\operatorname{prodexp}(m) \< \operatorname{prodexp}(n)\\$.

For example, \\$n = 8\\$ is a highly powerful number as we have \\$\operatorname{prodexp}(n) = 3\\$ and

| \\$m\\$ | \\$\operatorname{prodexp}(m)\\$ |
| --- | --- |
| \\$1\\$ | \\$1\\$ |
| \\$2\\$ | \\$1\\$ |
| \\$3\\$ | \\$1\\$ |
| \\$4\\$ | \\$2\\$ |
| \\$5\\$ | \\$1\\$ |
| \\$6\\$ | \\$1\\$ |
| \\$7\\$ | \\$1\\$ |

All of which are strictly less than \\$3 = \operatorname{prodexp}(8)\\$. Whereas \\$n = 7\\$ is not highly powerful as \\$\operatorname{prodexp}(7) = 1 \< 2 = \operatorname{prodexp}(4)\\$.

The first few highly powerful numbers are

```
1, 4, 8, 16, 32, 64, 128, 144, 216, 288, 432, 864, 1296, 1728, 2592

```

This is A005934 on OEIS.

---

This is a standard challenge. You may choose whether to

* Take a positive integer \\$n\\$ and output the \\$n\\$th highly powerful number (you may choose between 0 and 1 indexing)
* Take a positive integer \\$n\\$ and output the first \\$n\\$ highly powerful numbers
* Output all highly powerful numbers indefinitely

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

# Answer
> 6 votes
# Jelly, 11 bytes

```
1ÆEP$ÐṀḢ=Ɗ#

```

Try it online! Prints the first n numbers. -1 thanks to Jonathan Allan.

Brownie points acquired.

```
1           # Starting from 1
          # # Find the first n integers where...
 --------Ɗ  # Last three elements as a monad
        =   # Where the number equals
       Ḣ    # The first of
     ÐṀ     # The indicies of maximal elements by...
 ---$       # Last two elements as a monad...
   P        # Product of
 ÆE         # Exponents of prime factorisation of the number.

```

# Answer
> 5 votes
# Vyxal, 9 bytes

```
ɾ‡∆ǐΠ∴=)ȯ

```

Try it Online! Outputs the first n highly powerful integers. -1 thanks to lyxal.

```
        ȯ # First n positive integers
-------)  # Where...
     ∴    # Maximum of...
ɾ         # Range from 1 to n
 ‡---     # By...
    Π     # Product of
  ∆ǐ      # Prime exponents
      =   # Is equal to the number?

```

# Answer
> 4 votes
# 05AB1E, ~~13~~ ~~12~~ 9 bytes

```
∞ʒDLÓPZk-

```

Outputs the infinite sequence.

-3 bytes thanks to *@JonathanAllan*.

Try it online.

**Explanation:**

```
∞          # Push an infinite list of positive integers: [1,2,3,...]
 ʒ         # Filter it by:
  D        #  Duplicate the current value
   L       #  Pop one, and push a list in the range [1,value]
    Ó      #  Get the exponents of each inner integer's prime factorizations
           #  (which will include 0s, but this doesn't matter for the results)
     P     #  Get the product of each inner list
      Z    #  Push the maximum (without popping the list)
       k   #  Pop the maximum and list, and push the first (0-based) index of this max
        -  #  Subtract this 0-based index from the duplicated current value
           #  (only 1 is truthy in 05AB1E)
           # (after which the filtered infinite list is output implicitly as result)

```

# Answer
> 3 votes
# PARI/GP, 60 bytes

```
p=n=0;while(1,if(p<q=vecprod(factor(n++)[,2]),p=q;print(n)))

```

Attempt This Online!

Outputs all highly powerful numbers indefinitely.

---

## 57 bytes but would stack overflow

```
f(p,n)=f(if(p<q=vecprod(factor(n++)[,2]),print(n);q,p),n)

```

Attempt This Online!

# Answer
> 3 votes
# Nekomata, 9 bytes

```
Ňᵖ{Rƒᵐ∏Ɔ<

```

Attempt This Online!

```
Ňᵖ{Rƒᵐ∏Ɔ<
Ň           Any natural number
 ᵖ{         Check that:
   R          Range from 1 to the number
    ƒ         Factor each number
     ᵐ        Map:
      ∏         Take the product of exponents
       Ɔ<     Check that the last result is the largest

```

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

Output all highly powerful numbers indefinitely, as suggested by **@Arnauld**.

```
for(x=p=0n;;p<s&&(p=s,console.log(x)))for(d=s=++x;d;)x%d+d--**x%x&&--s

```

Try it online!

## JavaScript (Node.js), 72 bytes

Takes a positive integer \\$ n \\$ and returns the \\$ n \\$-th highly powerful number (1-indexed).

```
n=>eval('for(x=p=0n;n;p<s&&(p=s,n--))for(d=s=++x;d;x%d+d--**x%x&&--s)x')

```

Try it online!

# Answer
> 3 votes
# Charcoal, 60 bytes

```
ＮθＷ‹Ｌυθ«→≔ⅈη≔¹ζ≔¹εＷ⊖η«≦⊕ε≔⌕⮌Ｘ⁰↨ηε⁰δ≧÷Ｘεδη¿δ≧×δζ»¿⬤υ›ζκ⊞υζ»Ｉⅈ

```

Try it online! Link is to verbose version of code. Eventually outputs the 1-indexed `n`th highly powerful number (avoid `n>15` on TIO). Explanation:

```
Ｎθ

```

Input `n`.

```
Ｗ‹Ｌυθ«

```

Repeat until `n` record prime factorisation exponent product records have been found.

```
→≔ⅈη≔¹ζ≔¹ε

```

Increment the trial number and start to factorise it.

```
Ｗ⊖η«

```

Repeat until the trial number has been factorised.

```
≦⊕ε

```

Try the next potential factor.

```
≔⌕⮌Ｘ⁰↨ηε⁰δ

```

Find its multiplicity.

```
≧÷Ｘεδη

```

Divide the trial number by the prime power.

```
¿δ≧×δζ

```

Multiply the exponent product by the current exponent, if any.

```
»¿⬤υ›ζκ⊞υζ

```

If this is a record exponent product then save it.

```
»Ｉⅈ

```

Output the number with the `n`th record exponent product.

# Answer
> 2 votes
# Python3, 234 bytes

```
R=range
def P(n):
 d=[]
 while n>1:
  for i in R(2,n+1):
   if(i<3or all(i%j for j in R(2,i)))and 0==n%i:n//=i;d+=[i]
 r=1
 for i in{*d}:r*=d.count(i)
 return r
def f():
 n=0
 while(n:=n+1):
  if all(P(m)<P(n)for m in R(1,n)):print(n)

```

Try it online!

Prints the sequence indefinitely.

# Answer
> 2 votes
# Pyth, 15 bytes

```
.fqh.M*FhMr8PZS

```

Try it online!

Outputs the first \\$n\\$ terms in the sequence.

### Explanation

```
.fqh.M*FhMr8PZSZZQ    # implicitly add ZZQ
                      # implicitly assign Q = eval(input())
.f               Q    # Take the first Q items which are truthy over lambda Z
              SZ      #   range(1,Z+1)
    .M                #   filter this for elements which maximize lambda Z
            PZ        #     prime factors of Z
          r8          #     length encode
        hM            #     take just the lengths
      *F              #     reduce over multiplication
   h                  #   first element
  q             Z     #   is equal to Z

```

# Answer
> 2 votes
# Gaia, 17 bytes

```
⟨┅⟨ḋ_v2%Π⟩¦ṅ¤⌉>⟩#

```

Try it online!

Returns the first (1-indexed) `n` all-high-powerful numbers.

There's a quirk with numeric mode  where it returns a list `[prime,exponent]` for `n<4` and for `n>3` it returns a list `[[prime1,exponent1],...]`. I suppose that's what I get for golfing in a language that hasn't been updated in 6 years.

```
			; implicit input, n
⟨	       ⟩#	; find the first n positive integers where the following is truthy:
	   ṅ¤⌉>		; is the last element of the following list the unique maximum?
				; (literally, is the last element greater than the max of the remaining elements)
   ḋ_v2%Π  		; the product of the exponents in the prime factorization
 ┅⟨	 ⟩¦		; for each integer in the range 1..i (where i is the positive integer we're on now)

```

# Answer
> 1 votes
# Ruby `-rprime`, 75 bytes

Prints infinitely.

```
p m=e=1
2.step{|x|d=x.prime_division.reduce(1){_1*_2[1]};m,e=p(x),d if d>e}

```

Attempt This Online! (50ms timeout)

```
# -rprime imports Prime as a command line flag
p m=e=1                 # Print 1 while also setting m (current most powerful)
                        #   and e (current highest exponent product)
2.step{|x|              # Count up infinitely starting from 2, store as x
  x.prime_division      # Get prime factors of x
   .reduce(1){_1*_2[1]} # Multiply the exponent component of each factor together
d=                      # Set that value as d
m,e=p(x),d if d>e       # if d > e, print x, set m to x, and set e to d
}                       # End loop structure

```

# Answer
> 1 votes
# Wolfram Language (Mathematica), 72 bytes

Try it online!

```
p=n=0;While[1<2,n++;q=Times@@Last/@FactorInteger[n];If[p<q,p=q;Print@n]]

```

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


title: Irreducible polynomials over GF(5)

text:
# Question
Title: Irreducible polynomials over GF(5)
A polynomial with coefficients in some field *F* is called irreducible over *F* if it cannot be decomposed into the product of lower degree polynomials with coefficients in *F*.

Consider polynomials over the Galois field GF(5). This field contains 5 elements, namely the numbers 0, 1, 2, 3, and 4.

### Task

Given a positive integer *n*, compute the number of irreducible polynomials of degree *n* over GF(5). These are simply the polynomials with coefficients in 0-4 which cannot be factored into other polynomials with coefficients in 0-4.

### Input

Input will be a single integer and can come from any standard source (e.g. STDIN or function arguments). You must support input up to the largest integer such that the output does not overflow.

### Output

Print or return the number of polynomials that are irreducible over GF(5). Note that these numbers get large rather quickly.

### Examples

```
In : Out
 1 : 5
 2 : 10
 3 : 40
 4 : 150
 5 : 624
 6 : 2580
 7 : 11160
 8 : 48750
 9 : 217000
10 : 976248
11 : 4438920

```

Note that these numbers form the sequence A001692 in OEIS.

# Answer
> 10 votes
# Jelly, ~~30~~ ~~23~~ ~~22~~ 20 bytes

```
ÆF>1’PḄ
ÆDµU5*×Ç€S:Ṫ

```

Try it online! or verify all test cases at once.

### Algorithm

This uses the formula

$$\text{A001692}(n) = \frac 1 n \sum\_{d|n} \mu(d)5^\frac n d$$

from the OEIS page, where \\$d | n\\$ indicates that we sum over all divisors \\$d\\$ of \\$n\\$, and \\$\mu\\$ represents the Möbius function.

### Code

```
ÆF>1’PḄ       Monadic helper link. Argument: d
              This link computes the Möbius function of d.

ÆF            Factor d into prime-exponent pairs.
  >1          Compare each prime and exponent with 1. Returns 1 or 0.
    ’         Decrement each Boolean, resulting in 0 or -1.
     P        Take the product of all Booleans, for both primes and exponents.
      Ḅ       Convert from base 2 to integer. This is a sneaky way to map [0, b] to
              b and [] to 0.

ÆDµU5*×Ç€S:Ṫ  Main link. Input: n

ÆD            Compute all divisors of n.
  µ           Begin a new, monadic chain. Argument: divisors of n
   U          Reverse the divisors, effectively computing n/d for each divisor d.
    5*        Compute 5 ** (n/d) for each n/d.

       Ç€     Map the helper link over the (ascending) divisors.
      ×       Multiply the powers by the results from Ç.
         S    Add the resulting products.
          :Ṫ  Divide the sum by the last divisor (n).

```

# Answer
> 3 votes
# Mathematica, ~~39~~ 38 bytes

```
DivisorSum[a=#,5^(a/#)MoebiusMu@#/a&]&

```

Uses the same formula as the Jelly answer.

# Answer
> 3 votes
# Python 3, 59 bytes

```
f=lambda n:(5**n-sum(d*f(d)for d in range(1,n)if n%d<1))//n

```

Try it online!

This uses the formula

$$f(n) = \frac 1 n \sum\_{d|n} \mu(d)5^\frac n d$$

but applies Möbius inversion to turn it into

$$5^n = \sum\_{d|n} f(d) d$$

and solves for \\$f(n)\\$.

**55 bytes**

```
f=lambda n,d=1:d//n*5**n/n or f(n,d+1)-d*f(d)*(n%d<1)/n

```

Try it online!

Has float precision issues for larger inputs.

# Answer
> 2 votes
# Scala, 74 bytes

Port of @xnor's Python answer in Scala.

Use the formula: \\$5^n = \sum\limits\_{d|n} f(d) d\\$

Try it online!

```
n=>{(BigInt(5).pow(n)-(1 until n).filter(d=>n%d==0).map(d=>d*f(d)).sum)/n}

```

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

```
n->ffnbirred(5,n)

```

Try it online!

---

# Pari/GP, without built-in, 33 bytes

```
n->sumdiv(n,d,5^d*moebius(n/d))/n

```

Try it online!

---
Tags: code-golf, math, abstract-algebra, polynomials
---


# Question
Title: How many trailing zeros in the hyperfactorial?
We have a challenge to calculate the hyperfactorial and one to count the trailing zeros of the factorial, so it seems logical to put them together and count the trailing zeros in the hyperfactorial.

As a recap, the hyperfactorial of a number, H(n) is simply Πiⁱ, that is, 1¹·2²·3³·4⁴·5⁵·…·nⁿ. It can be defined recursively as H(n) = nⁿH(n-1) with H(0) = 1. This is integer sequence A002109.

Your task is to write the shortest program or function that accepts a non-negative integer `n` and returns or prints the number of trailing zeros in H(`n`) when represented as a decimal number (i.e. the corresponding entry from sequence A246839).

`n` will be in the range of integers in your language; H(`n`) might not be. That means your **program must terminate** given any non-negative `n` that's valid in your language (or 2³² if that's smaller).

Some test cases:

| input | output |
| --- | --- |
| 0 | 0 |
| 4 | 0 |
| 5 | 5 |
| 10 | 15 |
| 24 | 50 |
| 25 | 100 |
| 250 | 8125 |
| 10000 | 12518750 |

# Answer
# Python 3.8 (pre-release), 38 bytes

```
f=lambda n:n and(f(m:=n//5)-m*~m//2)*5

```

Try it online!

## How?

Calculates the number almost directly only recursing to correct for higher powers of 5 in the base:

$$\begin{align} f(n) & =\sum\_{i=5,10,...,n} i+\sum\_{i=25,50,...,n}i+\sum\_{i=125,250,...,n}i+... \\ & =5 \sum\_{i=1}^\left\lfloor\frac n 5 \right\rfloor i + 25 \sum\_{i=1}^\left\lfloor\frac n {25} \right\rfloor i + 125 \sum\_{i=1}^\left\lfloor\frac n {125} \right\rfloor i + ... \\ & = 5 \sum\_{i=1}^\left\lfloor\frac n 5 \right\rfloor i + 5 f\left(\left\lfloor\frac n 5 \right\rfloor\right) \\ & = 5 \frac{\left\lfloor\frac n 5 \right\rfloor\left(\left\lfloor\frac n 5 \right\rfloor+1\right)}2 + 5 f\left(\left\lfloor\frac n 5 \right\rfloor\right)\end{align}$$
> 20 votes

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

```
f=n=>n&&f(~-n)+g(n)*n
g=n=>n%5?0:-~g(n/5)

```

Try it online!

-3 bytes from Arnauld

# JavaScript (Node.js), 29 bytes

```
f=n=>n&&f(n=n/5|0)*5-n*~n/2*5

```

Try it online!

Port of loopy walt's
> 5 votes

# Answer
# Python 2, 58 bytes

```
f=lambda n:n and f(n-1)+g(n)*n
g=lambda i:i%5<1and-~g(i/5)

```

Try it online!

## Python 2, 39 bytes

```
f=lambda n:n and(f(n/5)-n/5*~(n/5)/2)*5

```

Try it online!

Port of loopy walt's Python answer.
> 4 votes

# Answer
# Charcoal, 16 bytes

```
ＩΣＥ⊕Ｎ×ι⌕⮌Ｘ⁰↨ι⁵¦⁰

```

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

```
    Ｎ               Input integer
   ⊕                Incremented
  Ｅ                 Map over implicit (inclusive) range
      ι             Current value
     ×              Times
          ⁰         Literal integer `0`
         Ｘ          Vectorised raise to power
            ι       Current value
           ↨        Converted to base
             ⁵      Literal integer `5`
        ⮌           Reversed
       ⌕            Find index of
               ⁰    Literal integer `0`
 Σ                  Take the sum
Ｉ                   Cast to string
                    Implicitly print

```
> 4 votes

# Answer
# C (gcc), 49 bytes

```
g(n){n=n%5?0:-~g(n/5);}f(n){n=n?f(~-n)+g(n)*n:0;}

```

Try it online!

*Port of l4m2 JavaScript answer*
> 4 votes

# Answer
# PARI/GP, 30 bytes

```
n->sum(i=1,n,i*valuation(i,5))

```

Attempt This Online!

Based on Michel Marcus's code on the OEIS page.
> 4 votes

# Answer
# C (gcc), 31 bytes

*port of loopy walt's Python answer.*

```
f(n){n=n?(f(n/=5)-n*~n/2)*5:0;}

```

Try it online!
> 4 votes

# Answer
# Vyxal `s`, 34 bitsv2, 4.25 bytes

```
ɾ:5Ǒ*

```

Try it Online!

-7 bits thanks to emanresu

## Explained

```
ɾ:5Ǒ*
ɾ      # The range [1, input]
 :     # Duplicated
  5Ǒ   # With the multiplicity of 5 of each number
    *  # Multiply that by the original list
# The s flag sums the list

```

Created with the help of Luminespire.
> 3 votes

# Answer
# Jelly, 5 bytes

```
ọ€5ḋR

```

A monadic Link that accepts a non-negative integer, \\$n\\$, and yields the number of trailing zeros of the hyperfactorial, \\$H(n)\\$.

**Try it online!**

### How?

As the hyperfactorial's input increases, each time \\$n\\$ reaches a multiple of five \\$n\nu\_5(n)\\$ more zeros are added.

```
ọ€5ḋR - Link: non-negative integer, n
 €    - for each {i in [1..n]}:
ọ 5   -   {i} order of multiplicity of {5}
    R - range {n} -> [1..n]
   ḋ  - dot-product

```
> 3 votes

# Answer
# Desmos, 47 bytes

```
f(k)=∑_{n=1}^knlog_5(gcd(n,5^{ceil(log_5n)}))

```

Try It On Desmos!

Try It On Desmos! - Prettified

It can be `f(k)=∑_{n=1}^knlog_5(gcd(n,5^n))` but that quickly runs into inaccuracies even for smaller inputs.
> 3 votes

# Answer
# 05AB1E, ~~16~~ 10 bytes

```
LDmTªPγθg<

```

-6 bytes thanks to *@lyxal*.

Actually calculates \\$H(n)\\$ and counts the amount of trailing 0s, so this is a much slower approach. Still valid though, since the new 05AB1E is built in Elixir, which has an infinitely large integer and is only limited by memory (in the legacy version of 05AB1E, built in Python, it would be valid as well for the same reason).

Try it online or verify (almost) all test cases.

**Explanation:**

```
L           # Push a list in the range [1, (implicit) input-integer]
 D          # Duplicate it
  m         # Take the power of the values at the same positions: [1**1,2**2,3**3,...]
   Tª       # Append a 10 to this list
     P      # Take the product
      γ     # Group adjacent equal digits together in substrings
       θ    # Pop and keep the trailing part of 0s
        g   # Pop and push its length
         <  # And decrease it by 1
            # (after which the result is output implicitly)

```

The  and `<` are only there for inputs in the range \\$0\leq n\<4\\$. For \\$n\geq5\\$ it works fine without it. These three bytes also have loads of alternatives (i.e. `LDmP0«γθ¦g`; `LDmPγθgDi0`; `LDmPγθgD≠*`; etc.), but I've been unable to find anything shorter thus far.

### Original ~~16~~ 12 bytes approach:

```
ƒNÐ5sm¿5.n*O

```

Port of *AidenChow*'s Desmos answer, so make sure to upvote that answer as well!

Try it online or verify all test cases.

**Explanation:**

```
ƒ             # Loop `N` in the range [0, (implicit) input-integer]:
 NÐ           #  Push three copies of `N` to the stack
 N 5sm        #  Pop one, and push 5 to the power `N`
 N    ¿       #  Pop this and another `N`, and push their Greatest Common Divisor
       5.n    #  Take log_5 of that value
 N        *   #  Multiply it by the remaining `N`
           O  #  Sum all values on the stack together
              # (after which the result is output implicitly)

```

05AB1E lacks the convenient `multiplicity`-builtin that the Jelly and Vyxal answers have, ~~although I still have the feeling this can be shorter with another approach, since the `5sm` and `5.n` are rather verbose.~~ EDIT: which was indeed correct.
> 3 votes

# Answer
# Excel, 68 bytes

```
=LET(a,SEQUENCE(A1),IFERROR(SUM(N(TEXTSPLIT(PRODUCT(a^a),,0)="")),))

```

Input in cell `A1`. Fails for `A1>7`.
> 2 votes

# Answer
# Retina 0.8.2, 47 bytes

```
.+
$*¶

$.`$*#$.`$*
+%`^(#+)\1{4}\b
$'¶$1
A`#
1

```

Try it online! Link includes Link includes faster test cases (since it calculates in unary internally, it times out TIO after about `3000` and probably runs out of memory anyway after about `30000`). Explanation:

```
.+
$*¶

$.`$*#$.`$*

```

Generate a range from `0` up to and including the input, in duplicated unary, once using `#` and once using `1`.

```
%`^(#+)\1{4}\b
$'¶$1

```

For each entry that has a multiple of `5` `#`s, remove them leaving the `1`s, and then append an entry with the number of `#`s divided by `5`, but with the original number of `1`s.

```
+`

```

Repeatedly process any new entries that have a multiple of `5` `#`s.

```
A`#

```

Remove all entries that weren't a multiple of `5` `#`s. (If they were, the `#`s would have been removed.)

```
1

```

Count the number of trailing zeros.

Retina 1 can do the whole calculation in decimal, allowing it to quickly compute the result for `10000`, although it does take 65 bytes:

```
.+
*¶

$.`
+%`.*50*$
$.(*2*
~["L$`^¶$.("|""L$rm`0*$
$.($:&*$&)$*_

```

Try it online! Link includes test cases. Explanation:

```
.+
*¶

$.`,$.`

```

Generate a range from `0` up to and including the input.

```
+%`.*50*$
$.(*2*

```

Double any value that ends in 5, 50, 500 etc. as many times as necessary so that it does not.

```
["L$`^¶$.("|""L$rm`0*$
$.($:&*$&)$*_

```

Multiply each original value by the number of trailing zeros, then generate a command that calculates the sum of those products. The intermediate multiplication allows use of a capture on the right which would otherwise have to be wrapped. The match is performed right-to-left so that values with trailing zeros are only matched once but matches without trailing zeros are also matched so that the match index will give the original value.

```
~`

```

Execute that command.
> 2 votes

# Answer
# Scala 3, 48 bytes

Port of @loopy walt's Python answer in Scala.

```
n=>{if(n<1)0 else{val m=n/5;(f(m)+m*(m+1)/2)*5}}

```

Attempt This Online!
> 2 votes

---
Tags: code-golf, factorial
---


# Question
Title: How drunk am I and when can I drive again?
It's weekend and what are the cool guys doing on weekends? Drinking of course! But you know what's not so cool? Drinking **and** driving. So you decide to write a program that tells you how loaded you are and when you are gonna be able to drive again without getting pulled over by the cops and loosing your license.

# The Challenge

Given a list of beverages you enjoyed this evening, calculate your blood alcohol level and the time you have to wait till you can hop into your car and get home.

# Input

Input will be a list of drinks you had this night. This will look like this:

```
4 shots booze
1 glasses wine
2 bottles beer
3 glasses water

```

*Containers will always be plural.*

As you can see each entry consists of:

* The type of drink (booze, wine, beer, water)
* The container for the drink (shots, glasses, bottles)
* The amount x of the drinks you had of that type as integer with x \> 0,

Each drink type adds a certain amount of alcohol to your blood:

```
booze ->  0.5 ‰ / 100 ml
beer  ->  0.1 ‰ / 100 ml
wine  ->  0.2 ‰ / 100 ml
water -> -0.1 ‰ / 100 ml

```

Water is the exception here, since it thins your blood out and lowers your alcohol level (would be so nice if that actually worked...).

Each container has a certain volume:

```
shots   -> 20 ml
glasses -> 200 ml
bottles -> 500 ml

```

# Output

You have to output two numbers:

* The alcohol level in ‰
* The time in hours you have to wait until you reached 0.5 ‰ or less, so you can drive again. You loose 0.1 ‰ per hour.

**Notes**

* The alcohol level can never fall below zero.
* Same goes for the waiting time. If you have 0.5 ‰ or less, output zero.
* The order of drinks does not matter, so drinking water may lower the alcohol level below zero in the process of the calculation. If it remains there, you need to replace it with zero.

The alcohol level for the the example above would be calculated like this:

```
4 shots booze   -> 0.4 ‰
1 glasses wine  -> 0.4 ‰
2 bottles beer  -> 1.0 ‰
3 glasses water -> -0.6 ‰

=> 0.4 + 0.4 + 1 - 0.6 = 1.2 ‰

```

To reach 0.5 ‰ you need to loose 0.7 ‰. You loose 0.1 ‰ per hour, so you need to wait 7 hours to drive again.

# Rules

* You can take the input in any format you want, but you have to use the exact strings as given above. You may take the numbers as integers.
* You can output the two numbers in any order, just make in clear which one you use in your answer.
* You may assume that the input will always have at least one entry.
* Function or full program allowed.
* Default rules for input/output.
* Standard loopholes apply.
* This is , so lowest byte-count wins. Tiebreaker is earlier submission.

# Test cases

Input as list of strings. Outputs alcohol level first, values seperated by a comma.

```
["4 shots booze","1 glasses wine","2 bottles beer","3 glasses water"] -> 1.2, 7
["10 shots booze", "1 bottle water"] -> 0.5, 0
["3 glasses wine", "2 bottles booze"] -> 6.2, 57
["6 shots beer", "3 glasses water"] -> 0, 0
["10 glasses beer"] -> 2.0, 15

```

**Happy Coding!**

# Answer
> 1 votes
# Javascript (ES6), 111

Takes input as arrays of arrays of strings/integers e.g.

```
[[4, "shots", "booze"],
[1, "glasses", "wine"],
[2, "bottles", "beer"],
[3, "glasses", "water"]]

```

**Outputs to simple array** e.g. `[1.2, 7]`

```
a=>(b=0,c={s:2,g:20,b:50,o:2,e:10,i:5,a:-10},a.map(([d,e,f])=>b+=d*c[e[0]]/c[f[1]]),g=b>0?b:0,[g/10,g>5?g-5:0])

```

#Explained

```
a => (
b = 0,                                           // Counter For Alcohol Level
c = {s:2, g:20, b:50, o:2, e:10, i:5, a:-10},    // Look up for values
a.map(                                           // Loops over array
  ([d, e, f]) =>                                 // Sets d,e,f to respective array indexes
     b += d * c[e[0]] / c[f[1]]                  // Increases Level by values from lookup
  ),
g = b > 0 ? b : 0,                               // If Level is lower than 0 make it = 0
[g / 10, g > 5 ? g - 5 : 0])                     // Output: Level / 10 and Level - 5 bound to 0

```

# Answer
> 7 votes
## TSQL, ~~301~~, ~~299~~, ~~219~~, 206 Bytes

Input goes into temp table `#I` (you said any format :)

```
SELECT * INTO #I FROM (
  VALUES
    (4,'shots','booze')
   ,(1,'glasses','wine')
   ,(2,'bottles','beer')
   ,(3, 'glasses','water')
) A (Q, V, N)

```

Code:

```
SELECT IIF(L<0,0,L),IIF(10*L-.5<0,0,10*L-.5)FROM(SELECT SUM(Q*S*P)L FROM(VALUES('bo%',.5),('be%',.1),('wi%',.2),('wa%',-.1))A(W,S),(VALUES('s%',.2),('g%',2),('b%',5))B(X,P),#I WHERE N LIKE W AND V LIKE X)A;

```

Thanks for the ideas to improve it, Micky T :)

# Answer
> 3 votes
# JavaScript (ES6), 131

```
a=>a.map(s=>([a,b,c]=s.split` `,t+=a*[50,20,2]['bgs'.search(b[0])]*~-'0236'['aeio'.search(c[1])]),t=0)&&[t>0?t/100:0,t>50?t/10-5:0]

```

**Less golfed**

```
a=>(
  t=0,
  a.map(s=>(
    [a,b,c] = s.split` `,
    t += a * [50,20,2]['bgs'.search(b[0])] // char 0 is unique
           * [-1,1,2,5]['aeio'.search(c[1])] // char 1 is unique
           // golfed: add 1 to get a string of dingle digits, the sub 1 using ~-
    )
  ),
  [ t>0 ? t/100 : 0, t>50 ? t/10-5 : 0]
)

```

# Answer
> 1 votes
# Perl, ~~133~~ 119 + 3 = ~~136~~ 122 bytes

```
%u=(o,.5,e,.1,i,.2,a,-.1,g,2,b,5,s=>.2);/(\d+) (.).* .(.)/;$x+=$1*$u{$2}*$u{$3}}{$_=($x>0?$x:0).$".($x-.5>0?$x-.5:0)*10

```

To be run with `perl -p`. Takes line-oriented input on STDIN, produces output on STDOUT.

Less-golfed version:

```
# char->number conversion table
# declared using barewords except for 's', which can't be a bareword
# because it's a keyword
%u=(o,.5, e,.1, i,.2, a,-.1, g,2, b,5, s=>.2);

# extract the number, first letter of first word, second letter of
# second word
/(\d+) (.).* .(.)/;

# do unit conversion and multiply up all factors
$x += $1 * $u{$2} * $u{$3}

# hack for -p to produce an END { ... print } block
}{

# format output
$_ = ($x > 0 ? $x : 0) . $" . ($x-.5 > 0 ? $x-.5 : 0)*10

```

Thanks to dev-null for suggestions saving 11 bytes.

# Answer
> 1 votes
# C (GCC), ~~176~~ 166 bytes

*-10 bytes thanks to @ceilingcat*

```
float x;main(a){for(char b[9],c[9];~scanf("%d%s%s\n",&a,b,c);)x+=a*(*b-98?*b-103?.02:.2:.5)*(*c-98?c[1]-97?2:-1:c[1]-111?1:5);printf("%f %f",x>0?x:0,fmax(0,x*10-5));}

```

Attempt This Online!

---
Tags: code-golf, arithmetic
---


title: Code that will only execute once

text:
# Question
Title: Code that will only execute once
**Goal**

The goal of this challenge is to write code that will execute once and only once. This means basically that it damages the program, script, or environment in some way. If rebooting the system allows the code to run again that is permitted.

**Scoring**

Number of votes. All assumptions must be clearly listed. Any answers just initiating a reboot or halt will be disqualified.

**Additional Rules because Greg Hewgill is a demi-god**

No root access is permitted.

**End Date**

The contest will close on May 31, 2014.

**Edit**

This contest has been changed to popularity contest.

# Answer
## Vigil

Finally a usecase for Vigil!

```
def main():
  raise Exception()

```

Excerpt from the "language specification":

> It goes without saying that any function that throws an exception which isn't caught is *wrong* and must be punished.
>
> ...
>
> If an oath is broken, the offending function \[...\] *will be duly punished.*
>
> How?
>
> **Simple: it will be deleted from your source code.**
>
> The only way to ensure your program meets its requirements to absolutely forbid code that fails to do so. With Vigil, it will do this for you *automatically.*

There are other ways to do this, because Vigil provides the keywords `implore` and `swear` which are basically oaths to adhere to certain pre- and post-conditions:

```
def main():
  swear 0 > 1

```
> 549 votes

# Answer
# Pretty much any Linux distro, 9 chars

This one is a classic!

```
#!/bin/rm

```

Put this in a file and run it:

```
> ed
a
#!/bin/rm
.
wq foo
> ls
Mail mbox foo
> chmod 777 foo
> ./foo
> ls
Mail mbox

```

Aaand it's gone!

As to what is going on: I'm really just running `rm`! `#!` is called a shebang. And if you put one of these followed by a path to some executable as the first line in your script, the program loader will execute your script file with whatever you wrote there - the default is usually `#!/bin/bash` or `#!/bin/sh` (Bourne-again shell / Bourne shell). The first argument passed to this script will be the filename itself (which is why you see so many solutions including `%0` or `$0` and the likes in here); so by making my file contain `#!/bin/rm` and running it, all I'm doing is passing the filename of my file to `rm`.
> 316 votes

# Answer
# x86 binary, 4 bytes

```
F0 0F C7 C8

```

Assumption: Must be run on a P5 Pentium CPU.

The above instruction is commonly known as the F00F bug. It attempts to execute an invalid instruction, prefixed with *lock*.

This freezes the CPU up completely (not a halt nor a reboot) and it doesn't even require root access.
> 263 votes

# Answer
# Bash, 5

```
>"$0"

```

Truncates itself to zero length.

If the filename doesn't contain spaces, `>$0` works for **3 chars**!
> 158 votes

# Answer
# gzip

```
#!/bin/gzip

```

To much annoyance to people used to nondestructive commandline tools, `gzip` by default ruins the original file, replacing it with a gzipped version (adding a suffix).

This is a variation on the `#!/bin/rm` option, except this one is recoverable by manual human intervention (call `gunzip` on it). As a special bonus, the resulting file is much longer than the original (the difference depends on the filename length).

Warning: location of `gzip` may vary.

EDIT: as pointed out by WChargin, this is more portable:

```
#!/usr/bin/env gzip

```

The rest of the file can have any content. It's essentially a file that, when called, hides itself in a box and refuses to come out until you forcibly unpack it.
> 154 votes

# Answer
# Bash, ~~13~~ 12

Not the shortest, but it doesn't actually delete the file or make the system unusable.

```
chmod 0 "$0"

```

If the filename doesn't contain spaces, you can remove the quotes to save 2 chars.

## Explanation

It removes all permissions (`rwx`) from itself. When you attempt to run it, or even view its code, a second time, without manually restoring the permissions, it will say something like

```
bash: <FILENAME>: Permission denied

```

Restore the permissions with

```
chmod +rwx <FILENAME>

```

## Old version

Only removes execute permissions, but one char longer (this was a question before it got changed to ):

```
chmod -x "$0"

```

## Sneaky version by Łukasz Niemier

```
#!/bin/chmod 0

```
> 126 votes

# Answer
# 6800 machine code - 1 byte

```
0xDD

```

This is known as HCF or Halt and Catch Fire
> 120 votes

# Answer
# Shell + sed, 16 bytes

Not quite as destructive as some of the other answers ;-)

This script inserts a comment `#` at the beginning of every line of itself:

```
sed -i s/^/#/ $0

```
> 100 votes

# Answer
## Commodore 64 BASIC

This one doesn't delete the program.

```
1 POKE 2048,1

```

According to the Commodore 64 memory map, address`2048`is unused, but it must contain a value of `0` so that the BASIC program can be RUN.
> 97 votes

# Answer
Assumption: Running Solaris, logged in as root

```
killall

```
> 95 votes

# Answer
# Batch: 5 Bytes

```
%0|%0

```

It is basically the forkbomb for Windows.

The app starts its first argument twice. Don't run it in a productive environment ;)
> 75 votes

# Answer
# Python, 18

```
open(__file__,'w')

```

Truncates the file by opening it in write-only mode.
> 73 votes

# Answer
# JavaScript

```
localStorage.x = eval(localStorage.x + localStorage.x)

```

The first time you run it, it'll run fine:

```
>>> localStorage.x = eval(localStorage.x + localStorage.x)
NaN

```

If you try to run it more (even if you refresh), you'll get an error:

```
>>> localStorage.x = eval(localStorage.x + localStorage.x)
ReferenceError: NaNNaN is not defined

```
> 61 votes

# Answer
IBM's CMS Operating System, which is a single-user operating system which runs as a guest under IBM's VM Hypervisor, has an interesting file-structure.

Files consist of three elements, File Name, File Type, and File Mode. The File Mode consists of two elements, a single alphabetic, which for ease of explanation can be regarded in a similar way to the Drive Letter for Windows/MS-DOS, and a single numeric digit.

The single numeric digit has meaning, http://publib.boulder.ibm.com/infocenter/zvm/v5r4/index.jsp?topic=/com.ibm.zvm.v54.dmsa3/hcsd0b10127.htm, and for this task it is the number 3 which is interesting:

> File Mode Number 3
> File mode number 3 means that files are erased after they are read. You can use file mode number 3 if you do not want to maintain copies on your minidisks or in your SFS directories.

So, spend hours writing your script and file it as \`LOST FOREVER A3'. Run it, it works first time. Set off home, job well done.

Note, no message is produced indicating the erasure. After all, everyone knows what that `3` means, don't they?

It is actually of course very useful. You can, once testing is complete, use the `3` for temporary files, and not have to clean up afterwards, because they are read-once files.
> 49 votes

# Answer
## Bash , 12

**Note: This is destructive.**

```
:(){ :|:&};:

```

It's the popular bash fork-bomb. It exponentially eats all memory and PID's locking up the system. A hard-reboot will allow the code to be run again though why would you want to do that?

---

## Bash , 10

```
:(){ :&};:

```

For two less chars, this eats your memory linearly.

---

## Bash , 7

```
w;PATH=

```

`w` is chosen as the shortest executable that I could think of.

This simply erases the path variable so the shell can't find `/usr/bin/w` the next time. Restarting the shell fixes it as the path is usually stored in `~/.profile`
> 47 votes

# Answer
## Commodore 64 BASIC

```
0 NEW

```

`NEW` deletes the program.
> 47 votes

# Answer
## C#

Shortest code for deleting self

```
Process.Start(new ProcessStartInfo("cmd.exe", "/C choice /C Y /N /D Y /T 3 & Del \"" + Assembly.GetExecutingAssembly().Location + "\""));

```

Code for making it unnoticeable in the UI

```
Process.Start( new ProcessStartInfo()
{
    Arguments = "/C choice /C Y /N /D Y /T 3 & Del \"" + Assembly.GetExecutingAssembly().Location+"\"",
    WindowStyle = ProcessWindowStyle.Hidden, CreateNoWindow = true, FileName = "cmd.exe"
});

```
> 22 votes

# Answer
## My Name's Shell...PowerShell

Classic self destructing message:

```
@'
##################################
Project X is a go

Meet Eagle 1 at WP Alpha

Further comms is hereby prohibited
##################################
This message will self destruct in
5 seconds
'@
5..1| %{$_;Sleep 1;}
"Goodbye"
rm $(.{$MyInvocation.ScriptName})

```
> 21 votes

# Answer
## Bash (5)

```
rm $0

```

Assuming you don't have spaces in the filename.
> 18 votes

# Answer
## C++ 71

The executable file "golf" is denied permission to run next time.

```
#include <stdlib.h>
int main()
{
system("chmod a-x golf");
return 0;
}

```

## JavaScript/HTML 137, 145 with console test

```
<script id="s">
function h(){
console.log(1);
var s=document.getElementById("s");
h=s.innerHTML;
h=h.replace("h","g");
s.innerHTML=h;
}

```
> 18 votes

# Answer
# sh

```
#!/bin/sh
curl http://runonce.herokuapp.com/

```

Will run only once (and it shows "Hello, world!" if it runs), even if you reinstall the system, and put the script again.

---

EDIT: I figured I would release a script behind runonce as well. Nothing special, as it wasn't supposed to be released either way, but whatever.

```
<?php
$db = pg_connect("[connection information]");
$ip = isset($_SERVER["HTTP_X_FORWARDED_FOR"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] : $_SERVER["REMOTE_ADDR"];

pg_query("DELETE FROM users WHERE time < now() - interval '1 day'");

$result = pg_query_params($db, "SELECT * FROM users WHERE ip = $1 LIMIT 1", array($ip));

if (!pg_fetch_row($result)) {
    echo "Hello, world!\n";
    pg_query_params($db, "INSERT INTO users (ip) VALUES ($1)", array($ip));
}

```

As well as database schema

```
CREATE TABLE users (
    ip inet PRIMARY KEY,
    time timestamp with time zone NOT NULL DEFAULT now()
);
CREATE INDEX ON users (time);

```

The data is stored in Heroku's database, feel free to check their privacy policy if you like. I don't check the data stored in a database, it's stored purely to allow the code to execute once.
> 16 votes

# Answer
# **PHP, ~~22~~ 20 chars**

```
<?=unlink(__FILE__);

```

EDIT: Removed two chars at end per comments.
> 15 votes

# Answer
# GW-BASIC, 20 bytes

```
1 COLOR 3
2 SCREEN 1

```

This is a fun one. `COLOR 3` sets the foreground color to cyan. `SCREEN 1` sets the output screen to one that does not have color. Therefore, you can run the program once, but if you try to run it again:
> 15 votes

# Answer
## Bash 9 8 Characters

```
nc -l 1&

```

Will only run once, because the port is blocked forever.
> 11 votes

# Answer
# Ruby,14

It rewrites the source code as the name of the program.

```
IO.write $0,$0

```
> 11 votes

# Answer
**NodeJS - 33 bytes**

```
require('fs').unlink(__filename);

```
> 11 votes

# Answer
# Batch (6 characters)

This is assuming we have permission to delete the file, and of course can be done on Windows (maybe MS-DOS as well).

```
del %0

```
> 10 votes

# Answer
## Batch, 7 chars

**Save unsaved work before trying this.**

Assumes either a 64-bit system, or a 32-bit system with \<2 GB RAM memory. Must be saved to a .bat or .cmd file before being launched, just entering it in cmd.exe won't work.

```
^ nul<^

```

It consumes a full CPU core and fills your RAM memory at a rate of several hundred megabytes per second. If you don't stop it in time (Task Manager), it will consume every byte of RAM on your computer, your entire system will freeze and you can't do anything before you forcibly shut down and restart your computer by means of cutting power or holding the power button down.

All credits go to txtechhelp on StackOverflow for this, see more information here: https://stackoverflow.com/q/23284131/1955334
> 10 votes

# Answer
# Sinclair BASIC

```
10 POKE 23635,255

```

Moves the address of the BASIC program in memory away from where it should be (203) so the wrong data is found by the interpreter.
> 9 votes

# Answer
# x86\_64 NASM Assembly for Linux

This assembly program replaces itself with its source code. It essentially "decompiles" itself, replacing the binary.

```
SECTION .data
    source incbin __FILE__
    len equ $ - source

SECTION .text
global _start

_start:

    pop rdi           ;number of parameters
    pop rdi           ;path to executable, parameter of unlink and open

    mov    rax, 87    ;unlink
    syscall
    cmp    rax, 0
    jl     error

    mov    rax, 2     ;open
    mov    rsi, 0101o ;O_WRONLY O_CREAT
    mov    rdx, 0600o ;permissions on created file
    syscall
    cmp    rax, 0
    jl     error
    mov    rdi, rax   ;file (return value of open)

    mov    rax, 1     ;write
    mov    rsi, source
    mov    rdx, len
    syscall
    cmp    rax, 0
    jl     error

    mov    rax, 60    ;exit
    mov    rdi, 0     ;return code
    syscall

    error:
        mov    rax, 60
        mov    rdi, 1
        syscall

```

Compile with:

```
nasm -f elf64 FILENAME
ld -m elf_x86_64 FILENAME.o -o FILENAME

```

Or the same thing in C (with inline assembly):

```
#include <stdio.h>

extern char src;
asm("src: .incbin \"" __FILE__ "\"\n.byte 0");

int main(int argc, char *argv[]) {
    unlink(argv[0]);
    FILE *file = fopen(argv[0], "w");
    fprintf(file, "%s",&src);
    fclose(file);
    return 0;
}

```

When run, the program deletes itself, and then writes its source code to the same path as the executable was at. That way, the deleted file can always be retrieved by recompiling, even if you lost the original source code.

There must be a better way to do this in C (or maybe not), but I don't know any.

Isn't that much better than just having it delete itself!
> 8 votes

# Answer
Here's a couple. Unlike many, these are not destructive, just creative and unorthodox.

# Bash

```
#!/usr/bin/env bash
read <<< ''
printf "$REPLY" > "$0"

```

This one's pretty simple. The variable `$REPLY` is created implicitly by `read`, but filled with an empty herestring. That empty string is then `printf`'ed into the current script. It is a rather obfuscated equivalent of the following:

```
#!/usr/bin/env bash
cat <<< '' > "$0" # probably a lot more portable

```

# Windows Batch

```
copy con %0 < nul

```

The second one basically copies the console input, read from `nul`, into the current file.
> 7 votes

# Answer
# Minecraft Command Block

```
setblock ~ ~ ~ air

```

When you run this in a command block, it destroys itself.
> 6 votes

# Answer
# x86 Machine Code (5 bytes)

HEX:

```
EA0000FFFF

```

ASM:

```
JMP FFFF:0000

```

You can try with `debug.exe`:

```
C:\>debug
-a 100
0AE7:0100 jmp ffff:0000
0AE7:0105
-g=100

```

**Explanation:** `BIOS`is always at `FFFF:0000` in memory. So this sequence boots the computer, if this is run in a protected command prompt in Windows it makes that process unresponsive.
> 5 votes

# Answer
**SQL**

```
create proc P as drop proc P

```

SQL Fiddle
> 5 votes

# Answer
# Error safe termination (Python 2/3)

```
from contextlib import contextmanager
@contextmanager
def suicide():
    try:    yield
    finally:
        open(__file__    , 'w')
        open(__file__+'c', 'w')

#-------------------------------------
# Error safe code ;)
#-------------------------------------
with suicide():
    print("Goodbye cruel world!")
    jump_off_building_______crash

```
> 5 votes

# Answer
## ARM Linux full standalone ELF, ~~50~~ ~~46~~ 45 bytes

```
7f 45 4c 46 01 00 00 00  00 00 00 00 00 00 01 00
02 00 28 00 21 00 01 00  21 00 01 00 04 00 00 00
01 98 0a 27 00 df 01 27  00 df 20 00 01

```

Adapted version of the code used in A Whirlwind Tutorial on Creating Really Teensy ELF Executables for Linux.

Assembler source (with raw encoded ELF header and comments, most of which are the same as in the article)

```
@ Adaptation of
@    https://www.muppetlabs.com/~breadbox/software/tiny/teensy.html
@ for an ARM binary which deletes itself. XD
@ $ arm-none-eabi-as -march=armv4t -mthumb runonce-arm.s -o runonce-arm.o
@ $ arm-none-eabi-ld -Ttext 0x00010000 runonce-arm.o -o runonce-arm.elf
@ $ arm-none-eabi-objcopy -O binary runonce-arm.elf runonce-arm

        .text              @ A lie.
        .arch   armv4t     @ Set architecture version
        .thumb             @ Needs to be Thumb to fit. ARM is too thicc.
        .syntax unified
        .org    0          @ Start at offset 0
Elf32_Ehdr:
        .byte   0x7F,'E','L','F'            @ e_ident
Elf32_Phdr:
        .word   1                                           @ p_type
        .word   0                                           @ p_offset
        .word   0x00010000 @ same as -Ttext                 @ p_vaddr
        .short  2          @ ET_EXEC        @ e_type        @ p_paddr
        .short  40         @ EM_ARM         @ e_machine
        .word   _start                      @ e_version     @ p_filesz
        .word   _start                      @ e_entry       @ p_memsz
        .word   4          @ Elf32_Phdr     @ e_phoff       @ p_flags

        @ Here is some space to put our code in.
        .thumb_func
        .globl _start
 _start:
        @ r0 = argv[0] from _start state
        ldr     r0, [sp, #4]                @ e_shoff       @ p_align
        @ unlink(argv[0])
        movs    r7, #0x0a  @ unlink
        svc     #0         @ syscall        @ e_flags
        @ exit(dontcare)
        movs    r7, #0x01  @ exit
        svc     #0         @ syscall        @ e_ehsize
        @ unreachable

        @ finish the header
        .short  0x20                        @ e_phentsize
        .byte   1                           @ e_phnum
        @ Truncated header because for some reason, Linux accepts this.

```

Basically, I took this program:

```
#include <unistd.h>
int main(int argc, char *argv[])
{
    unlink(argv[0]);
}

```

Or if it is easier to read,

```
main(c,v)int*v;{unlink(*v);}

```

And squeezed it into an ELF header using the method in that article, so it is 45 bytes with no dependencies on libc.

Works every time except when it is called from `$PATH`.
> 5 votes

# Answer
# Ruby, ~~15~~ 14

Put this line to a file (`del.rb`):

```
File.delete $0

```

then run it (self-destructive) : `ruby del.rb del.rb`
> 4 votes

# Answer
# PHP - 23

```
<?=fopen(__FILE__,'w');

```
> 4 votes

# Answer
# Coffescript

`_=->_=1`

compiles to:

```
var _;

_ = function() {
  return _ = 1;
};

```
> 4 votes

# Answer
# (noncompetitive)

```
ɟ`html”Ĭ)

```

`Try it here (Firefox only).`

Translates to `$('html').remove()` in Javascript.
> 4 votes

# Answer
# R, 7 Bytes

```
`=`=`$`

```

The code makes the "=" (used for assigning) become the "$" (used for subseting). After that it gives error.
> 4 votes

# Answer
# Bash: 4 chars

```
rm a

```

Put this in a file named **a** and run it on your Linux machine.
> 3 votes

# Answer
## Plain TeX - 31 (24) chars

```
\openout1=\jobname\write1{}\bye

```

If you save it as file `a.tex` then:

```
\openout1=a\write1{}\bye

```
> 3 votes

# Answer
# Bash

This deletes the file and makes sure that you can't recover it. So it definitely can't execute more than once.

```
shred "$0"

```

`shred` is a program to securely delete files by overwriting them. It's in coreutils.
> 3 votes

# Answer
# Dyalog APL (non-competing because it is too late)

```
f←⎕EX'f'∘⊣

```

`f` can only be called once. It needs an argument, which is ignored:

```
      f←⎕EX'f'∘⊣
      f 'dummy argument'
      f 'dummy argument'
VALUE ERROR
      f'dummy argument'
     ∧

```

It is a so-called "atop", which is a train of two functions. The left one is applied on the result of the right one.

The right function is `'f'∘⊣` which replaces any given argument with the string `'f'`.

The left function is `⎕EX`, which EXpunges the object named in its argument.

The first time around, `'f'∘⊣` returns `'f'`, which causes `⎕EX` to erase `f`. The second time around, calling `f` results in an error because `f` does not exist.

---

Here is one that can be tried online:

```
f←{f∘←¨}

```

After defining the function, the first time that it is called (with a dummy argument), e.g. `f 4`, the function ignores the argument, and instead redefines itself to be an operator (higher-order function). Now, operators need at least a left operand so when it is called again, the call will fail with a syntax error.
> 3 votes

# Answer
## AutoHotKey, 39 bytes

```
FileDelete %A_ScriptDir%\%A_ScriptName%

```

(Yes, I'm aware this is an ancient thread)
> 3 votes

# Answer
# Linux, 8 bytes

```
killall5

```

Similar to this answer, but this works on pretty much any Linux since System V and you don't need to be root. Don't believe me? Try it out on your Linux system! You'll want to save any work first...

I actually found this by accident when I was 11 messing around with Linux for the first time.

Links: killall5 manpage, recording
> 3 votes

# Answer
# Commodore 64 BASIC, 7 bytes

```
POKE 1,3

```

I've had a lot of fun in various BASIC dialects `POKE`-ing around in the first few memory storage locations. Here's the effect of this one:

Try it online! You'll have to type it in yourself.

Some other `POKE`s:

* `POKE 1,1` will freeze the system.
* `POKE 1,2` will clear the screen.
* `POKE 1,4` *completely kills* the system - the power button won't even work.
* `POKE 1,5` through `POKE 1,9` do the same as `POKE 1,4`, but with varying levels of destruction.
> 3 votes

# Answer
# TIS-100, 6 bytes

```
@0
HCF

```

The HCF (or halt and catch fire) command instantly crashes the TIS-100. The only way to run it again is to start it up again.
> 3 votes

# Answer
# R16K1S60 Assembly

```
mov [ax], ax

```

Simply overrides itself with with the contents of AX. the mov instruction is only one word large, so it deletes itself. Depends on AX being 0 (most releases guarentee this)

## Safe version

```
mov [0], ax

```

Depends on ax not being this specific instruction
> 3 votes

# Answer
# Wolfram Language (Mathematica): 37 Characters

```
Export[#,""]&/@FileNames[All,"C:/",∞]

```

Never tested this fully, but it should overwrite every single file on a Windows computer, including the Mathematica installation and the file the program is saved in by replacing all data with an empty string. Actually useful for quickly clearing out a folder, but most definitely not something I want to run.
> 3 votes

# Answer
# Haskell - 80 bytes

Pre base-4.6.0.0 : May not work on Windows. This depends on how the program is invoked.

```
import System.Environment
import System.Directory
main=getProgName>>=removeFile

```

Post base-4.6.0.0 : A bit longer but always works.

```
import System.Environment
import System.Directory
main=getExecutablePath>>=removeFile

```
> 2 votes

# Answer
**Shell script (Linux Bash); 4 characters**

```
rm *

```

*Warning ! Don’t try this at home.*

This shell script can be run only once. When run, this shell script will self-destruct.
> 2 votes

# Answer
**JAVASCRIPT** (~~35~~ 26 bytes when minified, in case that matters.) I know this is a late entry, but I had a situation where I considered being able to kill a function and decided it'd make a good entry here. (Still not sure if I'll actually use it.)

```
funny = function(){
  alert(0);
  window.funny = '';
};

funny();
funny();

```

*minified*

```
a=function(){alert(0);window.a=""};

```

*Alert isn't really needed*

```
a=function(){window.a=""};

```
> 2 votes

# Answer
# Python 2.7

```
import inspect
import os
for x in range(0, 2):
    os.remove(inspect.stack()[0][1])
    print "am I dead yet?"

```

It only runs 1/2 of a time.
> 2 votes

# Answer
# C, 56 chars

```
x[9];main(c,v)int**v;{sprintf(x,"rm %s",*v);system(x);}

```

Run on a UNIX system. By convention, the first string param passed to a C program is the executable name. This program simply deletes the executable (but leaves the source, which you have to recompile to run it again).
> 2 votes

# Answer
## oldschool DOS

---

You don't even need a compiler or interpreter, just the prompt. Not even reboot will let it run again once it completes (note: do not try on something you don't want to sacrifice. OS likely won't boot either.)

```
deltree C:\

```
> 2 votes

# Answer
## Windows batch, 4 bytes

```
.>%0
```

This will attempt to execute '.' as a command, while redirecting stdout to the original file, resulting in destruction of the original file.
> 2 votes

# Answer
# Scratch, 49 bytes

```
when gf clicked
wait until<(n)<(1
change[n v]by(2

```

Assuming `n=0`, which is the initial state of a variable when it is created.
> 2 votes

# Answer
# Python 24

Name the file `'q'`

```
import os
os.remove("q")

```
> 1 votes

# Answer
# PowerShell (37)

Save following code to a script file (test.ps1)

```
rm $MyInvocation.MyCommand.Definition

```

Run from command line:

PS \> .\test.ps1

Script will automatically delete itself.
> 1 votes

# Answer
**AppleScript ; 17 chars**

`delete document 1`

I was playing with more elegant solutions like this one :

`set the contents of the front document to ""`

But the action of `delete document 1` is even more fun !
> 1 votes

# Answer
# beeswax, 12 bytes

```
_8F+++P]f1Fw

```

Save this program under the name `!` and execute it.

```
              lstack                       gstack
_             [0,0,0]•                                          create bee
 8            [0,0,8]•                                          lstack 1st=8
  F           [8,8,8]•                                          all lstack=lstack 1st
   +++        [8,8,16]•                                         1st=1st+2nd
              [8,8,24]•                                         3 times
              [8,8,32]•
      P       [8,8,33]•                                         increment 1st
       ]      [8,8,2377900603251621888]•                        rotate bits of 1st by 2nd steps
        f                               [2377900603251621888]•  push lstack 1st ont gstack
         1    [8,8,1]•                                          lstack 1st=1
          F   [1,1,1]•                                          all lstack=lstack 1st
           w            write gstack to file. lstack 1st=bytes used for file name, lstack 2nd= used file content bytes.

```

If we look at the stack contents in hex, it gets clearer what’s happening:

`lstack[8,8,33]•` is `lstack[0x0000000000000008,0x000000000000008,0x0000000000000021]•` in hex.

If we rotate the bits of the 1st lstack value by 8 to the right, we get

`lstack[8,8,2377900603251621888]•`, which is

`lstack[0x0000000000000008,0x000000000000008,0x2100000000000000]•` in hex.

Instruction `f` pushes the 1st lstack value on the gstack:

`gstack[0x2100000000000000]•`

Now comes instruction w: First, the 4-byte words of the gstack get reinterpreted as a stack of UInt8 values:

`[0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x21]•`, in little endian order. The MSB is on top of the stack.

Instruction `w` takes the 1st lstack value as number of bytes taken for the file name, and the 2nd lstack value gives the number of bytes stored in the file. `lstack[1,1,1]•` means that 1 byte is taken as file name. `0x21` is the ASCII code for `!`, which is the name of the program itself. The next single byte (lstack 2nd), the value `0x00` is stored as file content, which is not executable as beeswax program.
> 1 votes

# Answer
## **Caché ObjectScript**, 12 bytes

```
k ^rOBJ($zn)

```

Output:

```
SAMPLES>do ^test

SAMPLES>do ^test

DO ^test
^
<NOROUTINE> *test

```
> 1 votes

# Answer
# q (14 bytes)

This program deletes itself when run.

```
hdel hsym .z.f

```
> 1 votes

# Answer
### Bash (7 characters)

```
TMOUT=1

```

It destroying the user session within a second by terminating the shell. See: man bash.

Example:

```
$ TMOUT=1
timed out waiting for input: auto-logout
Saving session...completed.

[Process completed]

```
> 1 votes

# Answer
# 8602/8610 machine code, 4 bytes

assuming that the program is stored at address $0800

```
78 4C 00 08

```

breakdown to assembler:

```
START    sei        // disable interupts
         jmp START  // endless loop

```

# C64 machine code, 3 bytes

```
4C E2 FC

```

this jumps to the builtin reset routine of the C64 (which, among other actions, clears the RAM)

run with `SYS <address>`
> 1 votes

# Answer
# OSI Challenger 1P

```
POKE 3,3

```

There are lots of BASIC answers because BASIC made the mistake of allowing users to directly access all memory. But this is the shortest `POKE` command yet. If only it was ...

You can try this here \- scroll down, hit Run, hit `C` to cold-boot, then `Enter`-`Enter` to get into BASIC mode. Then type `POKE 3,3` and watch the PC burn.
> 1 votes

# Answer
# Braingolf Inline Interpreter, 28 bytes \[non-competing\]

```
'''
open(__file__,'w')
a='''

```

Braingolf's Inline Interpreter treats the braingolf code as simply a multiline string within the Python3 interpreter.

This allows what is effectively an injection attack, where you can end the multiline string with three single quotes, then insert python code. The code will only run if you then begin a new multiline quote at the end, however.
> 1 votes

# Answer
# MOO, 24 bytes

```
delete_verb(this, verb);

```

Requires that this code is run as an actual verb, rather than through `eval` (or `$code_utils:eval_d`).
> 1 votes

# Answer
# JS, 8B

```
a=b=>a=0

```

calling `a` means `a=0`, thus `a` can't be called 2×.
> 1 votes

# Answer
# SmileBASIC

```
@memory_leak
If shift("this") then @memory_leak

```

There is a bug where using `POP()` or `SHIFT()` on a string literal causes a memory leak, and eventually there will not be enough memory left for the program to run. Trying to run it again will cause an error before the program starts.

`IF ... THEN @LABEL` is a shortcut for `IF ... THEN GOTO @LABEL`.
> 1 votes

# Answer
# AWK, 41 bytes

This script file overwrites itself with an empty string. Tested in `mawk` and `gawk`. Be aware that this only work in shell environments where the `_` variable is defined.

```
#!/bin/awk -f
BEGIN{print"">ENVIRON["_"]}

```
> 1 votes

# Answer
# JavaScript, 9 bytes in console

```
const a=0

```

throws an 'identifier already declared error' when run again
> 1 votes

# Answer
# Minecraft Function

```
datapack disable "file/pack"

```

Must be run as a function in a data pack named `pack`. Disables the data pack, thus making it impossible to run the function without re-enabling it.

Output from running `/function pack:function` twice:
> 1 votes

# Answer
# Bash: 2 chars

```
>a

```

Using inspiration from a couple of the other solutions, I came up with this solution in only two chars. Put this in a script called `a` and run it.

Just like the posts I got inspired by, this relies on the calling shell working around the missing `#!` line. Relying on this workaround is absolutely necessary, since you can't even produce a valid `#!` line in that space.

This happens if you let the kernel call it without a shell to work around the missing `#!` line:

```
$ strace ./a
execve("./a", ["./a"], [/* 47 vars */]) = -1 ENOEXEC (Exec format error)

```
> 0 votes

# Answer
## AutoIt - 27 bytes

Truncs itself to 0:

```
FileOpen(@ScriptFullPath,2)

```
> 0 votes

# Answer
# Batch (This isn't code golf)

```
echo "">%0.bat

```

Assumes you call it without the extension. If you are calling it with the extension, use `echo "">%0`.
> 0 votes

# Answer
# Vitsy, 8 bytes (I know it isn't Golf but I like to be concise)

```
iG" mr",
iG        Push name of self.
  " mr"   Push "rm " in front of it.
       ,  Execute as shell.
```

This assumes you run on a computer with `rm` as a command for delete. For an environment with `del` as its command for delete, it's 9 bytes (I think, I can't really test it):

```
iG" led",
iG        Push name of self.
  " led"  Push "del " in front of it.
        , Execute as shell.
```

It basically just deletes itself. :P
> 0 votes

# Answer
# Z80 ASM on TI-83/84 series

```
AsmPrgm
C3FFFF

```

If you put this into a TI-83 or 84 (any version, except 84+CE and CSE), the calculator will completely reset itself. Everything in RAM will be reset, including the program at hand.

For the TI84+CSE:

```
Asm84CPrgm
C3FFFF

```

Disclaimer: This might not work if you are running any apps that change the functionality of your calculator significantly. (i.e. libraries, non-official OS's)
> 0 votes

# Answer
# tcl, 7 bytes

```
vwait v

```

Explanation
> -1 votes

# Answer
**Bash file linux**

```
#!/bin/bash
shutdown -h now

```
> -3 votes

---
Tags: popularity-contest, stateful
---


title: Compute this fractal matrix

text:
# Question
Title: Compute this fractal matrix
The unique-disjointness matrix ( UDISJ(n) ) is a matrix on all pairs of subsets of `{1...,n}` with entries $$ U\_{(A,B)}=\begin{cases} 0, ~ if ~ |A\cap B|=1\\ 1, ~ otherwise \end{cases} $$

Or a bit less mathematical, it is the 2n times 2n matrix with a `0` in all entries where both indices have exactly one common `1` bit in their binary representation and a `1` in all other entries.

## Example:

```
      0   1  10  11  100 101 110 111
     _______________________________
0   | 1   1   1   1   1   1   1   1
1   | 1   0   1   0   1   0   1   0
10  | 1   1   0   0   1   1   0   0
11  | 1   0   0   1   1   0   0   1
100 | 1   1   1   1   0   0   0   0
101 | 1   0   1   0   0   1   0   1
110 | 1   1   0   0   0   0   1   1
111 | 1   0   0   1   0   1   1   1

```

Write a program or function that takes an integer `n` as input and outputs the corresponding \\$2^n \times 2^n\\$ matrix.

Rules:

* The values in the matrix can either be 0 / 1 (as numbers) or truthy/falsey
* You are **not** allowed to permute the rows/columns of the matrix
* This is the shortest solution (per language) wins
* Your solution only needs to handle `n` between `2` and `10` (inclusive)

First 4 elements:

```
n=1:
1 1
1

n=2:

1 1 1 1
1   1
1 1
1     1

n=3:

1 1 1 1 1 1 1 1
1   1   1   1
1 1     1 1
1     1 1     1
1 1 1 1
1   1     1   1
1 1         1 1
1     1   1 1 1

n=4:
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1   1   1   1   1   1   1   1
1 1     1 1     1 1     1 1
1     1 1     1 1     1 1     1
1 1 1 1         1 1 1 1
1   1     1   1 1   1     1   1
1 1         1 1 1 1         1 1
1     1   1 1 1 1     1   1 1 1
1 1 1 1 1 1 1 1
1   1   1   1     1   1   1   1
1 1     1 1         1 1     1 1
1     1 1     1   1 1 1   1 1 1
1 1 1 1                 1 1 1 1
1   1     1   1   1   1 1 1 1 1
1 1         1 1     1 1 1 1 1 1
1     1   1 1 1   1 1 1 1 1 1 1

```

# Answer
# Python, 72 bytes

```
lambda m:(q:=range(2**m))and(((i&j).bit_count()!=1for i in q)for j in q)

```

Attempt This Online!
> 7 votes

# Answer
# 05AB1E, 10 bytes

```
o<ÝDδ&b1ö≠

```

Outputs as a matrix with `1`s and `0`s.

Port of *@mousetail*'s Python answer, so make sure to upvote that answer as well!

Try it online or verify the first 5 test cases.

**Explanation:**

```
o           # Push 2 to the power the (implicit) input-list
 <Ý         # Pop and push a list in the range [0,2**input)
   Dδ&      # Create a bitwise-AND table of it:
   D        #  Duplicate the list
    δ       #  Pop both lists and apply double-vectorized:
     &      #   Bitwise-AND
      b     # Then convert each inner value to a binary-string
       1ö   # Vectorized-sum its digits by converting from base-1 to a base-10 integer
         ≠  # Check for each that it's NOT equal to 1 (0 if 1; 1 otherwise)
            # (after which the matrix is output implicitly)

```
> 7 votes

# Answer
# Jelly, 8 bytes

```
2ṗ«'`§’n

```

Try it online!

```
            (input: n)
2ṗ          nth Cartesian power of [1, 2]: for example,
              [[1,1,1,1], [1,1,1,2], [1,1,2,1], ..., [2,2,2,2]] if n=4
  «'`       self-table by vectorized minimum
     §      sum each vector
      ’     subtract 1
       n    not equal to… (implicit argument: n)

```

Instead of `0b0011 & 0b0110 = 0b0010` we do `1,1,2,2 « 1,2,2,1 = 1,1,2,1`.

Instead of checking popcount ≠ 1, we check sum ≠ n+1. `§’n` is shorter than `’§n1`.
> 7 votes

# Answer
# Vyxal, 66 bitsv2, 8.25 bytes

```
Eʁ:v⋏bvṠċ

```

Try it Online!

*-4.75 bytes thanks to TheThonnu*

The footer formats the resulting matrix into a nice grid like the test cases. Remove it for just a list of lists. Outputs inverted numbers (0s for 1s and 1s for 0s).

I somehow managed to generate like 3 other fractals while solving this, including an upside down triangle thing with the bottom off-center.

## Explained

```
EDẊ‹sƛƒ⋏bT₃;ẇ
ED             # Push three copies of n ** 2
  Ẋ            # Cartesian product of the range [1, n ** 2] and [1, n ** 2]
   ‹           # with all sublists decremented
    s          # and sorted
     ƛ     ;   # To each pair
      ƒ⋏       #   reduce by bitwise and
        bT₃    #   is the length of truthy indices 1?
            ẇ  # wrap into 2 ** n chunks

```

Created with the help of Luminespire.
> 6 votes

# Answer
# Thunno 2, 10 bytes

```
2RẉDȷỌ€ʂ⁻Q

```

Try it online!

Outputs a nested list. The footer formats it into the grid. Port of Lynn's Jelly answer.

#### Explanation

```
2RẉDȷỌ€ʂ⁻Q  # Implicit input
2Rẉ         # [1,2] to the cartesian power of the input
   DȷỌ      # Outer product over minimum with itself
      €ʂ    # Sum each inner list
        ⁻Q  # Decrement, not equal to the input?
            # Implicit output

```

Old:

```
OLDȷÆ&ıḃ1ȷcḅ  # Implicit input
OL            # Push [0..2**n)
  DȷÆ&        # Outer product over bitwise AND
      ıḃ1ȷc   # Popcount of each
           ḅ  # Equals one?
              # Implicit output

```
> 4 votes

# Answer
# Python, 66 bytes

```
lambda m:(q:=range(2**m))and[[(n:=i&j)>n^n-1for i in q]for j in q]

```

Attempt This Online!

mousetail's answer, but with bit operations instead of `bit_count`. We want to check that `i&j` (which we call `n`) doesn't have exactly one set bit, which means that it's a not power of two. We do this by checking that `n>n^n-1`, which is processed as `n>n^(n-1)`. Let's check that this works in every case:

* If `n` is a power of two, then `n-1` has disjoint bits set to `n` and so their XOR is greater than `n`.
* If `n` is any other positive value, then `n` and `n-1` share the same leading bit, and the XOR cancels this bit making the result smaller than `n`.
* For `n==0`, the result is `0`, the same as `n`.

Annoyingly Python doesn't let us do the walrus assignment `q:=range(2**m)` in the iterable of a list comprehension, so the code has it assigned beforehand. loopy walt points out a better way to handle the two levels of iteration is using the classic divmod two-loop trick together with the classic zip/iter chunker.

### 61 bytes

```
lambda m:zip(*2**m*[((n:=j&j>>m)>n^n-1for j in range(4**m))])

```

Attempt This Online!
> 4 votes

# Answer
# , ~~55~~ 53 bytes

```
function(n)(y=outer(x<-1:2^n-1,x,bitwAnd))^0-y%in%2^x

```

Try it online!

Rather than counting the number of on bits (which is very lengthy in R), tests the equivalent characterization of "equal to a power of 2"; then has to do some reshaping of the vector output of `%in%` to get back to the right shape matrix.
> 3 votes

# Answer
# Arturo, ~~57 54~~ 50 bytes

```
$->n[map^2n'x->map^2n=>[0<>^and dec<=<=and&-1x-1]]

```

Try it!

```
$->n[                     ; a function taking an argument n
    map^2n'x->            ; map over [1..2^n]; assign current elt to x
        map^2n=>[         ; map over [1..2^n]; assign current elt to &
            0<>           ; is zero not equal to
            and&-1x-1     ; bitwise and of current elts minus one
            <=<=          ; duplicated twice
            dec           ; minus one
            and           ; bitwise and
            ^             ; NOS to the TOS power
        ]                 ; end map
]                         ; end function

```
> 3 votes

# Answer
# Pyth, ~~15~~ 14 bytes

```
mmn1s&VdkQ=^U2

```

Try it online!

### Explanation

```
mmn1s&VdkQ=^U2Q    # implicitly add Q
                   # implicitly assign Q = eval(input())
          =^U2Q    # Q = repeated cartesian product of [0,1] Q times
m             Q    # map lambda d over range(Q)
 m       Q         #   map lambda k over range(Q)
     &Vdk          #     d & k, vectorized
    s              #     sum bits
  n1               #     != 1

```
> 2 votes

# Answer
# Nim, 119 bytes

```
import bitops
proc f(n:int)=
 let r=0..<1 shl n;for i in r:
  var s="";for j in r:s&= $int 1!=popcount i and j
  echo s

```

Attempt This Online!
> 2 votes

# Answer
# Jelly, 10 bytes

```
2*Ḷ&þ`B§n1

```

Try it online!

## How it works

```
2*Ḷ&þ`B§n1 - Main link. Takes n on the left
2*         - 2 ** n
  Ḷ        - [0, 1, ..., 2**n)
    þ`     - To every pair (a, b) in this range:
   &       -   Bitwise and
      B    - Convert all to binary
       §   - Sums
        n1 - Does not equal 1?

```
> 2 votes

# Answer
# BQN (CBQN), 45 bytes 22 ‘bytes’

```
{1≠+´¨∧⌜˜⥊∾⌜⍟(-1)˜↕2}

```

I think the following is slightly more elegant, and it's the same number of characters but, alas, more bytes.

```
{1≠+´∘∧⌜˜⥊(↕2)∾⌜⍟⋈⟨⟩}

```

We operate only on bit-strings, rather than integers. `⥊⌜⍟(-1)˜↕2` gives us the list of binary strings of length , which is then anded into a table, and summed: `+´∘∧⌜˜`. We then take only the `1≠` entries.

Attempt This Online!
> 2 votes

# Answer
# Ruby, ~~72 56~~ 54 bytes

```
->n{(w=0...1<<n).map{|i|w.map{|j|a=i&j;(a&a-1)**a>0}}}

```

Try it online!

This employs one of my favourite bit-twiddling hacks. `a&a-1` gives 0 if `a` has only one bit set. Unfortunately it also gives 0 if `a==0` so we use the fact that any number (including 0) raised to the power 0 is 1 to catch this special case: `(a&a-1)**a`.

So now we have distinction between nonzero and zero numbers. The rules require two distinct values, so we use `>0` to convert to `true/false` and we are done.

The footer in the linked TIO formats the output 2d array line by line, and converts the `true/false` to `1/0`.
> 2 votes

# Answer
# Factor \+ `math.matrices math.unicode`, 57 bytes

```
[ 2^ dup [ bitand bit-count 1 ≠ ] <matrix-by-indices> ]

```

Attempt This Online!

```
2^                           ! two to the input power
dup                          ! duplicate
[ ... ] <matrix-by-indices>  ! create an MxN matrix with indices on top of stack
bitand                       ! bitwise and
bit-count                    ! number of on bits
1 ≠                          ! not equal to one

```
> 1 votes

# Answer
# 05AB1E, 15 bytes

```
oDL<ãε`&b1¢Θ}sô

```

Try it online!

Outputs a nested list. The footer formats it into the grid. Port of lyxal's Vyxal answer.

*-1 thanks to @KevinCruijssen*

#### Explanation

```
oDL<ãε`&b1¢Θ}sô  # Implicit input
oD               # Push 2 ** n and duplicate
  L<ã            # Cartesian product of [0..2**n) with itself
     ε      }    # Map over this list:
      `&         #  Bitwise AND of the pair
        b1¢Θ     #  Is the popcount equal to 1?
             sô  # Split into 2 ** n chunks
                 # Implicit output

```
> 1 votes

# Answer
# Nibbles, 11 bytes

```
.;`,^2$.@!=1+``@`&@$

```

Attempt This Online!

Returns a matrix with truthy values (positive numbers) for `1` and falsy values (`0`) for `0`.
> 1 votes

# Answer
# Raku, 52 bytes

```
{(^$_ X+&^$_).rotor($_)».&{!$_||$_!=1+<.msb}}o 1+<*

```

Try it online!

The version of Raku on TIO fails to parse the `!$_||$_!=1+<.msb` bit, presumably due to a bug, so I've expressed it there as `!($_&&$_==1+<.msb)`, which is equivalent by De Morgan's law, but two bytes longer.

This is an anonymous function consisting of two separate anonymous functions composed together with `o`. The right-hand function is `1 +< *`, which shifts the number 1 leftwards a number of bits given by its argument; that is, two to the power of the argument. That number is passed to the left-hand function, where the variable `$_` gets its value.

* `^$_` is a range of numbers from 0 up to one less than `$_`. For example, when the number passed to the first function is 3, this is the range `0..7`.
* `X+&` gives the cross product of one copy of that range with another using the bitwise-and operator `+&`.
* `.rotor($_)` takes that flat crossed list and makes it into a square matrix.
* `».&{ ... }` recursively applies the code between the braces to each element of that matrix.
* `!$_ || $_ != 1 +< .msb` tests whether each number is zero (`!$_`) or consists of only a single binary digit by comparing the number to 1 bit-shifted left a number of places equal to the number's most significant bit (`1 +< .msb`).
> 1 votes

# Answer
# JavaScript (ES6), 74 bytes

```
n=>[...Array(1<<n)].map((_,y,a)=>a.map((_,x)=>(g=k=>k?k%2^g(k/2):1)(x&y)))

```

Try it online!
> 1 votes

# Answer
# Charcoal, 18 bytes

```
≔Ｘ²ＮθＥθ⭆θ¬⁼¹Σ↨＆ιλ²

```

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

```
  ²                 Literal integer `2`
 Ｘ                  Raised to power
   Ｎ                Input as a number
≔   θ               Save in variable
      θ             Saved variable
     Ｅ              Map over implicit range
        θ           Saved variable
       ⭆            Map over implicit range and join
               ι    Outer value
              ＆     Bitwise And
                λ   Inner value
             ↨   ²  Convert to base `2`
            Σ       Take the sum
         ¬⁼         Does not equal
           ¹        Literal integer `1`
                    Implicitly print

```
> 1 votes

# Answer
# PARI/GP, 51 bytes

```
n->matrix(2^n,,i,j,sumdigits(bitand(i-1,j-1),2)!=1)

```

Attempt This Online!
> 1 votes

# Answer
# Wolfram Language(Mathematica), 68 bytes

Golfed version. Try it online!

```
f@n_:=Array[Boole[1!=Tr@IntegerDigits[BitAnd[#-1,#2-1],2]]&,2^{n,n}]

```

Ungolfed version. Try it onlinne!

```
f@n_:=Table[If[Total[IntegerDigits[BitAnd[i-1,j-1],2]]!=1,1,0],{i,1,2^n},{j,1,2^n}]

```
> 1 votes

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

```
n=>[...Array(1<<n)].map((_,y,a)=>a.map((_,x)=>(x&=y)&&+!(x&x-1)))

```

Try it online!

na
> 1 votes

---
Tags: code-golf, math, matrix, fractal
---