# Question
Title: Draw the initial positions of Mölkky pins in ASCII art
Write a function (or a whole program) that outputs (or prints) an ASCII art of the initial position of Mölkky pins.

### Output :

```
    __    __    __
 __(07)__(09)__(08)__
(05)__(11)__(12)__(06)
|  (03)__(10)__(04)  |
|  |  (01)  (02)  |  |
|__|  |  |  |  |  |__|
   |__|  |__|  |__|
      |__|  |__|

```

### Rules :

* This is , so the shortest solution in bytes wins!
* Trailing spaces are allowed on each line
* *Additional* leading spaces (meaning, without counting the already mandatory leading spaces) are allowed **only if** there are the same number of *additional* leading spaces in each of the 8 mandatory lines
* *Additional* newlines are allowed at the beginning and at the end. These additional lines can contain any number of spaces

---

Thanks to Arnauld for the ASCII art and his advices concerning the challenge!

Despite the risk of just having to hardcode and/or compress the output, i hope the challenge will be interesting enough!

I intend to post my own answer in Javascript, but since i forced myself to do it without hardcoding, it has become quite long :')

# Answer
> 10 votes
# Python 3, 123 bytes

```
print(b'313a@B$""E""Q$6Q%Q$35Q#'.hex().translate(['__','|  ','  ',*'\n| ','(%02x)']*9)%(*b'	',))

```

Try it online!

## Explanation

This is a two-step compression. A dictionary coding is first applied so that certain chunks of recurring text is mapped to some number. The specific mapping is defined as follows:

```
0 -> '(%02x)'
1 -> '__'
2 -> '|  '
3 -> '  '
4 -> '\n'
5 -> '|'
6 -> ' '

```

The `%02x`s are converted to their corresponding values at the end by using a `%` formatting

The compressed string we get after applying the table above is `331331331461010101401010104201010324220303224512222251243651251251243335125123`. This string can then be uncompressed by using `str.translate()`.

A nice trick to compress this by roughly half is to use the `bytes.fromhex()` function, which interprets the string as a sequence of hex digits and converts it to a byte-string. Then to decode, we can use the inverse function, `bytes.hex()`. Fortunately, all of the hex digits are below `8`, so we can represent all the bytes directly without using any escape codes.

# Answer
> 6 votes
# JavaScript (ES6), 145 bytes

NB: Although I suggested the ASCII art in the sandbox, I didn't make any attempt to compress it until now. I would otherwise have waited before posting this answer.

*-1 thanks to emanresu A*
*-6 by removing trailing spaces, as suggested by l4m2*

This is 29 bytes shorter than hardcoding.

```
i=>`232323
3050505
05151504
60515046
66040466
76666676
2767676
227676`.replace(/./g,n=>"( )|"[n>>1]+(n>1?n&1?"__":"  ":n+"_798512630412"[i=-~i]))

```

Try it online!

### Encoding

The ASCII art is split into 8 distinct patterns of 3 characters:

```
0: "(0x"    4: ")  "
1: "(1x"    5: ")__"
2: "   "    6: "|  "
3: " __"    7: "|__"

```

The leading character of the \\$n\\$-th pattern is picked from the lookup string `"( )|"` at index \\$\lfloor n/2\rfloor\\$.

If \\$n\>1\\$, it is followed by either `" "` (2 spaces) if \\$n\\$ is even, or `"__"` if \\$n\\$ is odd.

If \\$n\le1\\$, we append \\$n\\$ as the tens digit and pick the units digit from the lookup string `"_798512630412"`, using the initially undefined argument \\$i\\$ of the function as a counter.

# Answer
> 5 votes
# Python 3, 137 bytes

```
for k in b"KHLHLHLHKLI	IIHKIIIQKNI\nIQNKNNQQNNKRNNNNNRNKHRNRNRNKHHRNRN":print(end=f"({k:02d}"*(k<13)or" )|\n"[k%4]+" _"[k%3]*2)

```

Try it online!

Each letter in the hardcoded string corresponds to a triple of characters, of one of `" )|\n"` followed by two copies of a space or underscore. The unprintable special characters correspond to pin numbers via their ASCII value. They're printed padded to two digits and preceded by an `(`.

Here's a version without unprintables:

**138 bytes**

```
for k in b"KHLHLHLHKLhIjIiIHKfIlImIgQKNdIkIeQNKNNbQcQNNKRNNNNNRNKHRNRNRNKHHRNRN":print(end=k//96*f"({k-97:02d}"or" )|\n"[k%4]+" _"[k%3]*2)

```

Try it online!

**152 bytes**

```
*s,="%23c"%10*8
t=3
for n in b"	\n\0":
 k=2
 for c in(n>0)*f"__({n:02})|  ||  ||__|":s[t+t//21*2+k-3//k+k//4*19]=c;k+=1
 t+=6
print(*s,sep='')

```

Try it online!

An alternative method with less hardcoding that turned out longer. Creates the ASCII art by starting with a blank canvas overlaying rectangles like this:

```
 __
(01)
|  |
|  |
|__|

```

with the corresponding pin numbers at the corresponding positions. Thanks to loopy walt for -2 bytes.

# Answer
> 4 votes
# K (ngn/k), ~~112~~ 110 bytes

```
`0:8 22#?[;;]//[176#"";i[<i]+\:5 2#+\"",7#4 18;{("__";x/"()"),"  _"^\:"|  |"}'-2$$w:101+<i:"HN/;(   5\""]

```

Try it online!

Places the pins top to bottom one after another in an initially empty grid.

Some of the strings contain unprintables that are swallowed by SE markdown. Click on the link to get the full code.

# Answer
> 4 votes
-1B from c--

# C (gcc), 150 bytes

```
i;f(c){for(i=0;c="226262425G5I5H41E5K5L5F031C5J5D30331A1B33037333337023737370223737"[i++];printf(c>64?"%02.f)":c&4?"__%c":"%3c",c-64.,"\n( |"[c%4]));}

```

Try it online!

# Answer
> 4 votes
# Python 3, 164 163 bytes

* -1 thanks to The Thonnu for the docstring implementation, very neat! I would never have thought to do this.

Very little I tried was shorter than a few substitutions and str repetitions. But, Im horrible at strings in python so please lmk if yall find something. I'm sure theres a better approach in totality and will be checking back on other answer to learn :)

```
a="  |__|"
print("    __"*3+"""
 __(07)__(09)__(08)__
(05)__(11)__(12)__(06)
|  (03)__(10)__(04)  |
|  |  (01)  (02)  |  |
|__"""+"|  "*5+"|__|\n",a*3+"\n   ",a*2)

```

Try it online!

# Answer
> 4 votes
# C (gcc) `-funsigned-char`, 144* bytes

```
i;main(c){for(;c=c/16?:"3333:\3033;\2003>\3633   6\3233! A! 3!!!32#2#2#!3!3"[i++];)printf(c&12?"(%02d)":L"\n |_"+c%4,c%16-3);}

```

Try it online!

There's some unprintable characters in the string, you should be able to see them on TIO.

\*: I wasn't able to insert some characters on TIO, you have to encode each octal char in the string as a single byte instead of an escape code. Here's the string and a bash script to build it locally:

## Try it locally

`str.c`:

```
#include <stdio.h>
char s[] = {
    0x11, 0x11, 0x33, 0x11, 0x11, 0x33, 0x11, 0x11, 0x33, 0x10,
    0x33, 0x3a, 0xc3, 0x33, 0x3b, 0x03, 0x80, 0x33, 0x3e, 0xf3,
    0x33, 0x09, 0x20, 0x11, 0x36, 0xd3, 0x33, 0x17, 0x21, 0x20,
    0x11, 0x12, 0x41, 0x11, 0x15, 0x21, 0x11, 0x02, 0x20, 0x33,
    0x12, 0x21, 0x11, 0x12, 0x21, 0x11, 0x12, 0x21, 0x33, 0x02,
    0x10, 0x11, 0x32, 0x23, 0x11, 0x32, 0x23, 0x11, 0x32, 0x23,
    0x10, 0x11, 0x11, 0x21, 0x33, 0x12, 0x21, 0x33, 0x02, 0x00,
};
int main(){fputs(s, stdout);}

```

**bash script**:

```
gcc -o str str.c
cat >molkky.c \
    <(printf %s 'i;main(c){for(;c=c/16?:"') \
    <(./str) \
    <(printf %s '"[i++];)printf(c&12?"(%02d)":L"\n |_"+c%4,c%16-3);}')
# verify size with `wc -c molkky.c`
gcc -w -funsigned-char -o molkky molkky.c

```

# Answer
> 3 votes
# Vyxal, 524 bitsv1, 65.5 bytes

```
»×3Ḃ≥tPkǔλu₍εc7Ėµz¤ꜝµ]¼εȮẎ-{Cḟȧ7x+¨Ȧ≥yĊ⁋»`
 %_|`τ»c;ṅm₴y„»₄τvS2↳›øb%

```

Try it Online!

A simple "encode everything as a magic number and base decompress" approach.

## Explained

```
»×3Ḃ≥tPkǔλu₍εc7Ėµz¤ꜝµ]¼εȮẎ-{Cḟȧ7x+¨Ȧ≥yĊ⁋»`
 %_|`τ»c;ṅm₴y„»₄τvS2↳›øb%

»×3Ḃ≥tPkǔλu₍εc7Ėµz¤ꜝµ]¼εȮẎ-{Cḟȧ7x+¨Ȧ≥yĊ⁋»   # The number 230294082147299956815045524104987124251723716866820093416899236760877183504036402931220223094
                                         `  # Converted to bijective base "<newline> %_|"
 %_|`
      »c;ṅm₴y„»₄τ                           # The list ⟨ 7 | 9 | 8 | 5 | 11 | 12 | 6 | 3 | 10 | 4 | 1 | 2 ⟩
                 vS                         # With each number converted to string
                   2↳                       # Padded to have a leading 0 if only one character
                      øb                    # Each surrounded in ()
                        %                   # Formatted into the bijective base converted string

 Created with the help of Luminespire at https://vyxal.github.io/Luminespire

```

# Answer
> 3 votes
# Ruby, ~~156~~ 147 bytes

```
puts"9kkdofqiz475318ru58n0ar9fnhjekvkdkkidk".to_i(36).digits(8).map{|y|"    __)__(%s)  |  |__
"[y*3,3]}.join%("070908051112060310040102".scan /../)

```

Try it online!

Second lazy attempt

# Answer
> 3 votes
# Bash, 147 bytes

```
sed 's/A/  /g;s/B/__/g;s/C/|  /g;s/D/)__(/g'<<E
AABAABAAB
 B(07D09D08)B
(05D11D12D06)
C(03D10D04)A|
CC(01D02)AC|
|BCCCCC|B|
A |BC|BC|B|
AAA|BC|B|
E

```

Try it online!

*Port of G B's Ruby answer*

# Answer
> 3 votes
# 05AB1E, 67 bytes

```
•1wÕ—VîaÉîñG)ùǝn\ιÏòáð×т}í(¿°ç÷É¡¤©•"_ |a(
)"ÅвJº'a•ëç‰ÊÉ&.åÈž•¦S.;

```

Try it online.

**Explanation:**

Step 1: Generate halve the shape with dummy value for the numbers:

```
•1wÕ—VîaÉîñG)ùǝn\ιÏòáð×т}í(¿°ç÷É¡¤©•
               # Push compressed integer 32061609852501126428829348223954853956247903207401179145663962432977933413421358
"_ |a(\n)"Åв   # Convert it to custom base-"_ |a(\n)", which basically converts it to
               # base-length, and indices each value into this string
            J  # Join this list of characters to a single multiline string

```

Try just step 1 online.

Step 2: Mirror it to have the full shape:

```
º              # Horizontally mirror the multiline string

```

Try the first two steps online.

Step 3: Replace the dummy value with the numbers at the correct positions:

```
'a            '# Push string "a"
•ëç‰ÊÉ&.åÈž•   # Push compressed integer 1070908051112060310040102
            ¦  # Remove the leading 1
S              # Convert it to a list of digits
 .;            # Replace every first occurrence of "a" in the multiline string one by
               # one with these digits
               # (after which the result is output implicitly)

```

I've used this 05AB1E tip to generate the code of step 1.
See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `•1wÕ—VîaÉîñG)ùǝn\ιÏòáð×т}í(¿°ç÷É¡¤©•` is `32061609852501126428829348223954853956247903207401179145663962432977933413421358` and `•ëç‰ÊÉ&.åÈž•` is `1070908051112060310040102`.

# Answer
> 3 votes
# Ruby, 132 bytes

```
a=(" "*22+$/)*j=9
"|0/923-71+\\)".bytes{|i|m=j+=i/13*2
"!GCC@".bytes{|k|a[m,n=k/16]=("|__|  |(%02d)"%i%=13)[k%8,n];m+=21+n/2}}
$><<a

```

Try it online!

Looped version of the below. Explanation to follow.

# Ruby, 139 bytes

```
a=(" "*22+$/)*j=8
"|0/923-71+\\)".bytes{|i|a[j+=i/13*2,4]="(%02d)"%(i%13)
a[j-22,2]="__"
a[j+23,4]=a[j+46,4]="|  |"
a[j+69,4]="|__|"}
$><<a

```

Try it online!

A full program that creates a canvas of 8 lines of 22 spaces and a newline, modifies it by adding the pins one by one from top to bottom, and then prints it.

The characters in the magic string are in the format `(number of characters to advance from the previous pin) * 13 + (value of pin)`

It should be possible to golf this quite a bit by drawing each pin line by line from top to bottom using a loop instead of hardcoding each line of the pin.

# Answer
> 3 votes
# Python, 130 bytes

```
A="%25c"%10*9;k=60
for j in b"ouS_7I!-'Y=C"*6:k-=1;j+=k//12%8%6*25;A=A[:j-4]+f" __ |  ||__|({-k:02})"[k//24*4:][:4]+A[j:]
print(A)

```

Attempt This Online!

## How?

Draws all the pins "simultaneously" line-by-line bottom up so stuff that should be hidden gets overwritten.

### Python, 150 bytes

```
A='';h="|      "
for*c,z in*"_  |_|_","|  ":h='|'+2*z+h[:7];A=(h[:3:-1]+h[:6]+h+"\n"+A).replace(*c or(4*'|',"(%02x)"),14)
print(A%(*b'	',))

```

Attempt This Online!

Not good enough to compete with the xnors and dingledoopers of this world but I still kind of like it.

### How?

Uses the approximate facts that the figure is left-right symmetric and each half's lines can be obtained sequentially by shifting the previous line by three characters (up to a wobble in the centre) to "procedurally" generate the figure. The final number insertion is stolen from dingledooper.

# Answer
> 2 votes
# JavaScript (Node.js), 279 bytes

Solution without hardcoding, which was kind of a hell to write.
But i needed to be exactly sure how much longer it was than the output itself!

```
_=>[...Array(128)].map((_,i)=>(a=i%16)+0*(d=p=>Math.abs(8-a)/2+Math.abs((b=1+i/16|0)-p))(0)?a%2?d(4.5)<=5&b>1?d(2)<=5&b<6?")("[(a/2+b|0)%4%2]:'|':' ':d(2)%4&(d(2)<5&b<5|d(2)==7|i==104)?'__':d(3)<4&b>1&b<6&i!=72?((t=d(2.5)==1.5)?"":"0")+(14-d(3)-b*2+(a+b>11)+t*4):'  ':`
`).join``

```

Try it online!

---

(i'll add some explanations when i'll have more time to get back into this code)

# Answer
> 2 votes
# Racket \- 404 bytes

I didn't want to hardcode the string (even though it would've made life easier). I spent roughly half of today trying to encode the string BY HAND and came up with this solution. I do believe there is a simpler encoded solution, but I had fun :)

```
#lang racket
(let([? char=?])(display(string-join(map(λ(c)(cond[(? c #\a)"    "][(? c #\b)"__"][(? c #\c)"\n"][(? c #\d)"__(0"][(? c #\e)")__(0"][(? c #\f)")__\n(0"][(? c #\g)")__(1"][(? c #\h)"|  (0"][(? c #\i)")  |"][(? c #\j)"|  "][(? c #\k)")  (0"][(? c #\l)"  |"][(? c #\m)"__|"][(? c #\n)"\n  "][else(string c)]))(string->list"abababc d7e9e8f5g1g2e6)ch3g0e4icjh1k2ilc|mlllllmn |mlmlmna|mlm"))"")))

```

Try it online!

---

## Explanation

We first convert the encoded string into a list via `string->list`. We pass this to `map` which passes the encoded character `c` a `lambda` function to test whether `c` matches any defined options. If it does, we return the corresponding string, otherwise we just return `c` as is. After the `map` is finished, we join all the results together and display the single string.

```
(let ([? char=?])
  (displayln
   (string-join
    (map (lambda (c)
           (cond [(? c #\a) "    "]
                 [(? c #\b) "__"]
                 [(? c #\c) "\n"]
                 [(? c #\d) "__(0"]
                 [(? c #\e) ")__(0"]
                 [(? c #\f) ")__\n(0"]
                 [(? c #\g) ")__(1"]
                 [(? c #\h) "|  (0"]
                 [(? c #\i) ")  |"]
                 [(? c #\j) "|  "]
                 [(? c #\k) ")  (0"]
                 [(? c #\l) "  |"]
                 [(? c #\m) "__|"]
                 [(? c #\n) "\n  "]
                 [else (string c)]))
         (string->list "abababc d7e9e8f5g1g2e6)ch3g0e4icjh1k2ilc|mlllllmn |mlmlmna|mlm"))
    "")))

```

---

## Output

```
    __    __    __
 __(07)__(09)__(08)__
(05)__(11)__(12)__(06)
|  (03)__(10)__(04)  |
|  |  (01)  (02)  |  |
|__|  |  |  |  |  |__|
   |__|  |__|  |__|
      |__|  |__|

```

*Have an amazing day everyone :)*

# Answer
> 2 votes
# Charcoal, 62 bytes

```
Ｆ⪪”←＆∧÷⊘ＦsＫ⦃ＮlE"Φ➙⁺¡﹪!⌕~⎇⸿¤”¶«⸿Ｆ⪪ι «Ｍ³→¿κ«→↗↑³↙)  ↑³↗(⟦__κ ω__

```

Try it online! Link is to verbose version of code. Explanation: Corresponds to @xnor's 154-byte Python approach, although I hadn't seen it at the time.

```
Ｆ⪪”←＆∧÷⊘ＦsＫ⦃ＮlE"Φ➙⁺¡﹪!⌕~⎇⸿¤”¶«

```

Split the compressed string  `07 09 08\n05 11 12 06\n 03 10 04\n 01 02"` on newlines and loop over each row.

```
⸿

```

Start a new row of output.

```
Ｆ⪪ι «

```

Split the row on spaces and loop over each column.

```
Ｍ³→

```

Move to the next column.

```
¿κ«

```

If there is a pin at this position, then...

```
→↗↑³↙)  ↑³↗(⟦__κ ω__

```

... draw the pin without moving the cursor.

The cursor actually starts at the cell below the first `_` in the bottom row. It moves right and then up and right, then draws three `|`s up, then draws the `)` and two spaces diagonally down and left (the first of these spaces overwrites one of any `_` from a previous pin), then draws three `|`s up again for the left of the pin, the draws the `)` up and right, then draws 5 lines of text `__`, pin number, space, nothing, `__`, leaving the cursor where it started.

# Answer
> 2 votes
# Jelly, 69 bytes

I was expecting this method to result in more terse code than this, oh well...

```
+ȷṾṫ-Ø(j“Ẓ“m³ṭ’ṃ“#%&$”©¤js4;Ɱ;ƭ@ƒ@
“'EçS¬aßQ35%C‘d5ṃ⁶Ėç/€»/Y®,“| _”¤y

```

A full program taking no arguments that prints the ASCII art, or a niladic Link that yields a string including the newline characters.

**Try it online!**

### How?

Creates each pin in the correct location on its own using characters below `(` and greater than  in an order\* such that they may then be merged using `»` (maximum) and finally translates this string into one with the expected characters.

* Also uses different characters for the `_` at the top of a pin and the `_` at the bottom of a pin so they merge in a different order.

```
+ȷṾṫ-Ø(j“Ẓ“m³ṭ’ṃ“#%&$”©¤js4;Ɱ;ƭ@ƒ@ - Link 1: int PinNumber; lists of space characters [R, C]
+ȷ                                 - {PinNumber} add 1000
  Ṿ                                - unevaluate -> list of characters
   ṫ-                              - tail from index -1 -> two characters with the leading zero if need be
     Ø(j                           - "()" joined with {that} -> e.g. PPN = "(07)"
                       ¤           - nilad followed by links as a nilad:
        “Ẓ“m³ṭ’                    - [190, 6908225]
                “#%&$”             - "#%&$"
                      ©            - (copy "#%&$" to the register for later use)
               ṃ                   - base decompress {[190, 6908225]} with digits {"#%&$"}
                                       -> ["%&&%", "#%%##%%##$$#"]
                        j          - join {that} with {PPN}
                         s4        - split into chunks of length four
                                       -> e.g. ["%&&%", "(07)", "#%%#", "#%%#", "#$$#"]
                                ƒ@ - start with {that} and reduce with {[r, c]} applying:
                              ƭ@   -   alternate between these with swapped arguments:
                           ;Ɱ      -     map with concatenate
                             ;     -     concatenate
                                     -> pin made of #%&$ characters at its desired location

“'EçS¬aßQ35%C‘d5ṃ⁶Ėç/€»/Y®,“| _”¤y - Main Link: no arguments
“'EçS¬aßQ35%C‘                     - code page indices = [39,69,23,83,7,97,21,81,51,53,37,67]
              d5                   - div-mod by five -> [[7,4],[13,4],[4,3],[16,3],[1,2],[19,2],[4,1],[16,1],[10,1],[10,3],[7,2],[13,2]]
                ṃ⁶                 - base decompress {that} with digits [space character]
                  Ė                - enumerate -> [[1,["       ", "    "]], [2,...], ...]
                   ç/€             - reduce each using Link 1 as a dyad
                      »/           - reduce by maximum (vectorises)
                        Y          - join with newline characters -> X
                                ¤  - nilad followed by link(s) as a nilad:
                         ®         -   recall "#%&$" from the register
                          ,“| _”   -   pair with "| _"
                                 y - translate {X} with mapping {["#%&$", "| _"]}
                                       N.B. $ translates to _ as well as & as it is out of range
                                   - (if running as a program) implicit print

```

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


title: Landmine Number IV

text:
# Question
Title: Landmine Number IV
## Background

You have again x3 been given the task of calculating the number of landmines in a field. But this time, we have no landmine number, and some landmines have exploded.

You must calculate the landmine score given a string of numbers. This is the landscape.

You have no landmine number to start with. Instead, the landscape has gaps where possible landmines may have exploded. It may also be the case that the gaps did not have a landmine.

For each gap in the landscape, represented by a space, add and multiply the digits left and right of it to gain two candidates for the landmine number.

For example, given `1 3`, two candidates would be 1+3 = 4 and 1\*3 = 3.

After doing this for all gaps, the number most often given as a result of calculations (highest count) is the landmine number.

If there are ties for the highest number count, the landmine number is the largest number in the tie.

For each time the result occurs as the calculated landmine number, add the landmine number to the landmine score.

Note: The very first and last digits will always have numbers, never gaps. There will also never be two immediately consecutive gaps.

## Your Task

* Sample Input: The number landscape, which will only contain numbers and spaces. It is given that if there are no gaps, return 0.

This cannot be taken as a list of numbers (eg. taking `02 24` as `['02', '24']`) or seperate inputs but it can be taken as a list of characters/ single digit numbers (eg. taking `02 24` as `['0', '2', ' ', '2', '4' ]`). This is because the landscape is one entity, and could easily have used a different character other than space.

* Output: Return the landmine score.

**Explained Examples**

```
Input => Output
178 9 11 => 72

The possible landmine numbers are:
8+9 = 17
8*9 = 72
9+1 = 10
9*1 = 9

These all occur once, so we choose the largest number within the tie, which is 72.

```

```
Input => Output
12 32 21 32 22 => 20

Possible landmine numbers:
2+3 = 5
2*3 = 6
2+2 = 4
2*2 = 4
1+3 = 4
1*3 = 3
2+2 = 4
2*2 = 4

Count:
2 = 1
3 = 2
4 = 5

The highest count is 5, for 4. So 4 is the landmine number. We add 4 5 times to get the landmine score, 20.

```

```
Input => Output
999910 10 10 10 10 10 10 => 6

Possible landmine numbers:
0+1 = 1, which occurs 6 times.
0*1 = 0, which occurs 6 times.

The highest count is 6 and it is tied, so we choose the largest number in the tie, 1. We add this 6 times to get the landmine score, 6.

```

```
Input => Output
2746 27362 4815 383 6 21 745 => 40

Possible landmine numbers:
6+2 = 8
6*2 = 12
2+4 = 6
2*4 = 8
5+3 = 8
5*3 = 15
3+6 = 9
3*6 = 18
6+2 = 8
6*2 = 12
1+7 = 8
1*7 = 7

Count:
6 = 1
7 = 1
8 = 5
9 = 1
12 = 2
15 = 1
18 = 1

The highest count is 5, for 8. So 8 is the landmine number. Finally, we add 8 5 times to get the landmine score, 40.

```

**Test Cases**

```
Input => Output
178 9 11 => 72
999910 10 10 10 10 10 10 => 6
2746 27362 4815 383 6 21 745 => 40

 => 0
19383 => 0
1 1 1 1 1 1 1 1 1 1 => 18
187373 28377373 2837821 2837 => 12
000 001 010 011 100 101 110 111 => 0
10 11 12 13 14 15 16 17 18 19 20 => 16
28478382847738212848392928626188 => 0
28478382847 7382128483 92928626188 => 49

```

This is , so shortest answer wins.

...

**Landmine Number Series**

# Answer
> 5 votes
# Excel (ms365), 151 bytes

Formula in `B1`:

```
=IFERROR(LET(s,TEXTSPLIT(A1,," "),r,DROP(RIGHT(s),-1),l,DROP(LEFT(s),1),v,VSTACK(r*l,r+l),m,MAP(v,LAMBDA(y,SUM(N(v=y)))),@SORTBY(v,m,-1,v,-1)*MAX(m)),)

```

# Answer
> 4 votes
# 05AB1E, 23 bytes

```
ü3ʒðk}εþDOsP‚}˜{RÐ.MQÏO

```

Input as a list (with spaces as gaps).

Try it online or verify all test cases.

**Explanation:**

```
ü3         # Push all overlapping triplets of the (implicit) input-list
  ʒ  }     # Filter this list of triplets by:
   ðk      #  Get the 0-based index of " ", or -1 if it isn't in the triplet
           #  (only 1 is truthy in 05AB1E, so only triplets with spaces in the middle
           #  are kept)
  ε        # Then map over each remaining triplet:
   þ       #  Remove the space by only leaving numbers
    D      #  Duplicate it
     O     #  Sum this pair
    s      #  Swap so the pair is at the top again
     P     #  Take the product of this pair
      ‚    #  Pair them together
       }˜  # After the map: flatten it to a single list
{R         # Sort this list and reverse it, so it's sorted from highest to lowest value
  Ð        # Triplicate this list
   .M      # Pop one list, and push the first most frequent number
     Q     # Check which values are equal to this most frequent max
      Ï    # Only keep the values at those truthy positions
       O   # Sum them together
           # (after which the result is output implicitly)

```

# Answer
> 3 votes
# JavaScript, 96 bytes

```
s=>~s.map(m=o=(c,i)=>p=c<'0'?[p*s[++i],p-s[i]].map(n=>m=--o[o[n]||=n/1e4,n]>o[m]?m:n):-c)&m*o[m]

```

```
f=

s=>~s.map(m=o=(c,i)=>p=c<'0'?[p*s[++i],p-s[i]].map(n=>m=--o[o[n]||=n/1e4,n]>o[m]?m:n):-c)&m*o[m]

testcases = `
178 9 11 => 72
999910 10 10 10 10 10 10 => 6
2746 27362 4815 383 6 21 745 => 40
 => 0
19383 => 0
1 1 1 1 1 1 1 1 1 1 => 18
187373 28377373 2837821 2837 => 12
000 001 010 011 100 101 110 111 => 0
10 11 12 13 14 15 16 17 18 19 20 => 16
28478382847738212848392928626188 => 0
28478382847 7382128483 92928626188 => 49
3 => 0
`.match(/^.* => .*$/gm).map(r => r.split(' => '));
testcases.forEach(([i, e]) => {
  console.log(e == f([...i]), f([...i]));
});
```

# Answer
> 3 votes
# Scala, 234 bytes

Golfed version. Try it online!

```
s=>{val n=s.split(' ');val c=mutable.Map[Int,Int]().withDefaultValue(0);for(i<-1 to n.length-1){val l=n(i-1).last.asDigit;val r=n(i)(0).asDigit;c(l+r)+=1;c(l*r)+=1};if(c.isEmpty)0 else{val m=c.values.max;c.filter(_._2==m).keys.max*m}}

```

Ungolfed version. Try it online!

```
import scala.collection.mutable

object Main {
    def landmineScore(s: String): Int = {
        val numbers = s.split(' ')
        val counts = mutable.Map[Int, Int]().withDefaultValue(0)

        for (i <- 1 until numbers.length) {
            val l = numbers(i - 1).last.asDigit
            val r = numbers(i).head.asDigit

            val sums = l + r
            val prods = l * r

            counts(sums) += 1
            counts(prods) += 1
        }

        if (counts.isEmpty) 0
        else {
            val maxCount = counts.values.max
            val maxNums = counts.filter { case (_, v) => v == maxCount }.keys
            maxNums.max * maxCount
        }
    }

    def main(args: Array[String]): Unit = {
        val testCases = List(
            "178 9 11",
            "999910 10 10 10 10 10 10",
            "2746 27362 4815 383 6 21 745",
            " ",
            "19383",
            "1 1 1 1 1 1 1 1 1 1",
            "187373 28377373 2837821 2837",
            "000 001 010 011 100 101 110 111",
            "10 11 12 13 14 15 16 17 18 19 20",
            "28478382847738212848392928626188",
            "28478382847 7382128483 92928626188"
        )

        testCases.foreach(tc => println(s"Input: $tc => Output: ${landmineScore(tc)}"))
    }
}

```

# Answer
> 3 votes
# Perl 5, 86 bytes

```
s/. (?=(.))/$h{$_}++for$&+$1,$&*$1/ge;($_)=sort{$h{$b}-$h{$a}||$b-$a}keys%h;$_*=$h{$_}

```

Try it online!

# Answer
> 3 votes
# Retina, 82 bytes

```
Lv$`. (.)
$.(*_$1*)¶$.(*$1*
^$
0
N`
N^$`(.+)(¶\1)*
$#2
L$`^(.+)(¶\1)*
$.(*$($#2*__

```

Try it online! Link includes test cases. Explanation:

```
Lv$`. (.)
$.(*_$1*)¶$.(*$1*

```

Get the sums and products of the digits adjacent to spaces.

```
^$
0

```

If there are none then insert a dummy product.

```
N`

```

Sort them.

```
N^$`(.+)(¶\1)*
$#2

```

Sort them in descending order of frequency.

```
L$`^(.+)(¶\1)*
$.(*$($#2*__

```

Multiply the mode by its count.

# Answer
> 2 votes
# JavaScript (Node.js), 97 bytes

```
x=>~x.replace(k=/. (?=(.))/g,(a,b)=>[-a*b,-a-b].map(v=>x=x<(t=k[v]=k[v]-1||v/99)?x:t))&x%1*99*~-x

```

Try it online!

-1 from Arnauld

# Answer
> 2 votes
# Python 3.8 (pre-release), 135 bytes

```
lambda l:-(m:=max(l:=sorted(-w for x,y,z in zip(l,l[1:],l[2:])if y==' 'for w in eval(f'{x}+{z},{x}*{z}'))or [0],key=(c:=l.count)))*c(m)

```

Try it online!

## Explanation

* `for x,y,z in zip(l,l[1:],l[2:])`: Iterate over each triplet of 3 consecutive elements
* `if y==' '`: Skip when the middle element is not a space
* `for -w in eval(f'{x}+{z},{x}*{z}')`: Append negative of the sum and product of first and third elements to list. These are the negated landmine number candidates. `eval` is used to avoid having to convert to int using `int`
* `l:=sorted(...)`: Iterate over the sorted negated landmine candidates. Ensures that bigger magnitudes appear first. Update the list `l` to this list.
* `lambda l:-(m:=max(...,key=(c:=l.count)))*c(m)`: Find the max value of the negated landmine number candidates when sorted by number of occurrences, multiply by the number of occurrences, and then negate the result. Because we sorted before, most negative numbers appear first, and `max` will take the first occurring element when their is a tie, which is also the largest when negated. Set `c:=l.count` to save bytes.

# Answer
> 2 votes
# R, 225 bytes

```
s=strsplit(x, '')[[1]];i=s==' ';s=as.double(s);if(any(i)){l=as.data.frame(table(sapply(X=which(i),FUN=function(X)c(s[X-1]+s[X+1],s[X-1]*s[X+1]))),stringsAsFactors=F);y=max(l[,2]);z=max(as.double(l[(l[,2]==y),1]));z*y;}else{0}

```

Try it online!

Readable version:

```
get_lms <- function(x) {
  chars = strsplit(x, '')[[1]]
  idx = chars==' '
  nums = as.double(chars)
  if(any(idx)){
    lm_cts = as.data.frame(
      table(
        sapply(X = which(idx),
               FUN = function(X) c(nums[X-1] + nums[X+1],
                                   nums[X-1] * nums[X+1]))
      ), stringsAsFactors = F);
    hi_cnt = max(lm_cts[,2]);
    hi_num = max(as.double(lm_cts[(lm_cts[,2]==hi_cnt),1]));
    hi_num*hi_cnt
  }
  else { 0 }
}

all(get_lms("178 9 11") == 72
    ,get_lms("12 32 21 32 22") == 20
    ,get_lms("999910 10 10 10 10 10 10") == 6
    ,get_lms("2746 27362 4815 383 6 21 745") == 40
    ,get_lms("") == 0
    ,get_lms("19383") == 0
    ,get_lms("1 1 1 1 1 1 1 1 1 1") == 18
    ,get_lms("187373 28377373 2837821 2837") == 12
    ,get_lms("000 001 010 011 100 101 110 111") == 0
    ,get_lms("10 11 12 13 14 15 16 17 18 19 20") == 16
    ,get_lms("28478382847738212848392928626188") == 0
    ,get_lms("28478382847 7382128483 92928626188") == 49)

```

# Answer
> 2 votes
# Charcoal, 42 bytes

```
ＦＥ⌕Ａθ ✂θ⊖ι⁺²ι⊞⊞ＯυΣιΠι≔⌈Ｅυ№υιηＩ∨⌈×Φυ⁼№υιηη⁰

```

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

```
ＦＥ⌕Ａθ ✂θ⊖ι⁺²ι

```

Loop over all of the slices of length `3` centred on spaces.

```
⊞⊞ＯυΣιΠι

```

Push the sum and product of that slice to the predefined empty list. Note that sum and product of a string splits the string on non-digit characters, casts the pieces to number and then takes the sum or product of the resulting list, although for single digits this is equivalent to the digital sum or product.

```
≔⌈Ｅυ№υιη

```

Get the highest frequency of any of the values.

```
Ｉ∨⌈×Φυ⁼№υιηη⁰

```

Multiply by the highest value with that frequency, or output `0` if there were no spaces in the input.

# Answer
> 1 votes
# Vyxal `s`, 128 bitsv2, 16 bytes

```
⌈zƛ÷h$t"⌊₍∑Π;fsṘĠÞG

```

Try it Online!

Takes input as a string. Ports Husk.

## Explained

```
⌈zƛ÷h$t"⌊₍∑Π;fsṘĠÞG
⌈z                   # Split the input on spaces and get all overlapping pairs
  ƛ         ;        # To each pair:
   ÷h$t"             #   [pair[0][-1], pair[-1][0]]
        ⌊            #   Each converted to int
         ₍∑Π         #   [sum, product]
             fs      # Flatten and sort the result
               ṘĠ    # Reverse and group by consecutive value
                 ÞG  # Get the longest by length
# The s flag sums the resulting list

```

Created with the help of Luminespire.

# Answer
> 1 votes
# Husk, 17 bytes

```
Σ►LgOΣẊ~§e+*→←†iw

```

Try it online!

## Explanation

```
Σ►LgOΣẊ~§e+*→←†iw
                w   Split input on spaces.
              †i    Convert each character to integer.
      Ẋ             For each adjacent pair of numbers:
       ~    →←      take the last digit from the first and the first digit from the second
        §e+*        and build a list with the sum and product of those digits.
     Σ              Concatenate all the lists obtained.
    O               Sort the values smallest to largest
   g                Group equal values together
 ►L                 Take the longest group (later groups chosen in case of equal length)
Σ                   Sum all values from this group together

```

# Answer
> 1 votes
# Jelly, 17 bytes

I feel like the last seven bytes may be able to be six somehow

```
ḲṚ+ż×ɗḢɗƝFfⱮÆṃ$ṀS

```

A monadic Link that accepts a list of integers (the digits) and space characters (the gaps) and yields an integer (the landmine score).

**Try it online!**
Note: Jelly cannot accept a mixed list of integers and characters when running as a *full program* as it interprets `' '` as a string
(e.g. an argument of `[1, ' ', 2]` would give the Main Link `[1, [' '], 2]`).

### How?

```
ḲṚ+ż×ɗḢɗƝFfⱮÆṃ$ṀS - Link: list of integers [0-9] & (single) space characters, Field
Ḳ                 - split {Field} at space characters
        Ɲ         - for each neighbouring pair (LeftInts, RightInts):
       ɗ          -   last three links as a dyad:
 Ṛ                -     reverse {LeftInts}
     ɗ            -     last three links as a dyad:
  +               -       {ReversedLeftInts} add {RightInts}
    ×             -       {ReversedLeftInts} multiply {RightInts}
   ż              -       {Added} zip {Multiplied}
      Ḣ           -     head
         F        - flatten -> PossibleLandmineNumbers
              $   - last two links as a monad:
            Æṃ    -   mode -> MostCommonValues
           Ɱ      -   for V in {MostCommonValues}:
          f       -    {PossibleLandmineNumbers} filter keep {V}
               Ṁ  - maximum
                S - sum

```

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


title: Big numbers: Ultrafactorials

text:
# Question
Title: Big numbers: Ultrafactorials
# Ultrafactorials

The ultrafactorials are a sequence of numbers which can be generated using the following function:

$$a(n) = n! ^ {n!}$$

The resulting values rise extremely quickly. *Side note: This is entry A046882 in the OEIS. Also related are the hyperfactorials, a still quite huge, but a bit smaller sequence: A002109*

# Your task

Your task is to implement these numbers into your language. Your program will calculate the **sum of all ultrafactorials** from 0 up to *inclusive* `n`.

## Input

Your program may only take one input: a number, which resembles the last \\$a(n)\\$ ultrafactorial to be added to the sum. The Input is assured to be positive or 0.

## Output

Your output is all up to you, as long as there's the visible sum of the numbers somewhere.

## Rules

* You can assume all integers, therefore integer input, and using integer counting loops to produce some results.

## Test cases

```
Input: -1
Output: Any kind of error (because -1! is undefined), or no handling at all

Input: 0
Output: 1

Input: 1
Output: 2

Input: 2
Output: 6

Input: 3
Output: 46662
```

# Challenge

This is , so the answer with the least length in bytes wins!

# Answer
> 7 votes
# 05AB1E, 5 bytes

Code:

```
Ý!DmO

```

Explanation:

```
Ý       # Take the range [0, ..., input]
 !      # Map factorial over each element
  Dm    # Exponentiate each element to itself
    O   # Take the sum

```

Uses the **CP-1252** encoding. Try it online!

# Answer
> 17 votes
# Mathematica, 19 bytes

```
Sum[n!^n!,{n,0,#}]&

```

Apologies for the extremely clear code ;)

# Answer
> 8 votes
# Jelly, 6 bytes

Try it online!

```
‘Ḷ!*`S // Main link: Argument n (integer)
‘      // Take n, increment by 1
 Ḷ     // Range from [0..n]
  !    // Calculates factorial for each [0..n]
   *`  // Raises each [0!..n!] to the power of itself
     S // Sum the resulting array

```

# Answer
> 7 votes
## R -  ~~34~~  30 bytes

```
x=factorial(0:scan());sum(x^x)

```

vectorizing is nice

**edit:** saved 4 bytes thanks to @MickyT

# Answer
> 4 votes
# Perl 6, ~~41~~ ~~38~~ 37 bytes

```
{[+] ([**] [*](1..$_)xx 2 for 0..$_)}

```
~~```
{[+] ([**] ([*] 1..$_)xx 2 for 0..$_)}

```~~ ~~```
{sum (($_**$_ with [*] 1..$_) for 0..$_)}

```~~

(Try it online.)

### Explanation:

* `for 0 .. $_`: For each integer from 0 to the input,
* `[*](1 .. $_) xx 2`: calculate the factorial twice,
* `[**] ...`: and exponentiate the two identical factorials.
* `[+] ...`: Then sum all results of the loop.

*Thanks to b2gills for 1 byte.*

# Answer
> 4 votes
# J, ~~15~~ 12 bytes

Saved 3 bytes thanks to miles!

```
1#.i.^~@!@,]

```

## Explanation

```
1#.i.^~@!@,]  input: y
          ,]  append y to list...
   i.         [0, y)
        !@    factorial each member
     ^~@      raise each to itself
1#.           perform summation

```

## Test cases

```
   f =: 1#.i.^~@!@,]
   (,. f"0) i.4
0     1
1     2
2     6
3 46662
   (,. f"0) i.6
0           1
1           2
2           6
3       46662
4  1.33374e33
5 3.17504e249

   echo"1] _90]\":f 6x
190281878633201797429473437859705759836595323046380462211756876146775419721154680216391116
383660154937824558291984804764687140715927099993629348072943551413397410741069111169123658
220861477766905534108349401724389611558474171816216027733366046875815097164882588181826712
426524007417126023680300953790645455254723360874298622143752208989152655091222094594342956
890526202094068774356589887610542642450567071133028553816930267473112879050178461179814798
008667622200592591542432361632955904924276854403585221477449385731481108378608652069211835
448555831555820393949831627809528917004144455150642180845929102272754394116905511650997561
389917179995442329297103257850695109383021080317204810134810158543814178231002423431556657
737982683316707709406053569620116083909440177269311235173671447595521339849978144493268530
780365729831790064477684808893338190825461650933123545889305523546630119181308584140916288
912561260392366609493077363059677222110731132927863243720195975705161197786520981159422881
575250362836779593393897664990291828935858671453835924398316498051705698128484688847592380
831018330553151156822298060174230201841578757499203145955456593022852288527824268115043999
037373974753999860179933517198889966353093307592136928730661270863274130109304971274296438
682725017433937245229524959283895094220677649257613358344409711070780405579776000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
000000003175042373780336892901667920556557182493442088021222004926225128381629943118937129
098831435345716937405655305190657814877412786176000000000000000000000000000000000000000000
000000000000000000000000000000000000000000001333735776850284124449081472890438

```

# Answer
> 3 votes
# Cheddar, ~~44~~ 37 bytes

```
n->(0|>n=>(i,a=(1|>i)/(*))->a**a)/(+)

```

Thank goats for reduce operator! I think it would've been good idea to add factorial

Try it online

## Ungolfed

```
n -> ( 0|>n => (i, a=(1|>i) / (*)) -> a ** a) / (+)

```

## Explanation

**Note:** A little outdated, will fix

```
n ->           // Input
( 0 |> n) =>   // Run below for each of [0, n]
    (
      i,           // Input
      a =          // Let's keep n! in this variable `a`
         (1 |> i)  // Range from [1, n]
         / (*)     // Multiply all the items of that range
                   // `/` is reduce `(*)` is multiplication function
    ) ->
    a ** a         // A to the power of A
) / (+)        // Sum all results

```

# Answer
> 3 votes
# MATL, 7 bytes

```
Q:Ygt^s

```

Try it online!

### Explanation

```
Q         % Take input n implicitly. Add 1
 :        % Range [1 2 ... n+1]
  Yg      % Gamma function, element-wise. This gives [0! 1! ... n!]
    t^    % Rise result to itself, element-wise
      s   % Sum all values. Implicitly display

```

# Answer
> 3 votes
# Ruby, ~~64~~ 66 bytes

```
->n{(o=(1..n).map{|i|a=(1..i).inject(:*);a**a}.inject(:+))?o+1:1}

```

Added two characters for the off-by-one bugfix (will look into shortening the inject calls later).

# Answer
> 3 votes
# PHP, 49 bytes

```
for($f=1;$i<=$argv[1];$f*=++$i)$s+=$f**$f;echo$s;

```

`INF` for `n>5` on a 64 bit system.

**for large numbers, 70 bytes**

```
while($i<=$argv[1])$s=gmp_add($s,gmp_pow($f=gmp_fac($i++),$f));echo$s;

```

requires PHP to be compiled with `--with-gmp`

# Answer
> 2 votes
# Haskell, ~~67~~ 56 bytes

Note that this submission was made *before* the rules that banned builtins were removed.

```
p=product
a n=sum[p[x|x<-[p[1..i]],_<-[1..x]]|i<-[0..n]]

```

For example:

```
*Main> a 0
1
*Main> a 1
2
*Main> a 2
6
*Main> a 3
46662
*Main> a 4
1333735776850284124449081472890438
*Main> a 5
3175042373780336892901667920556557182493442088021222004926225128381629943118937129098831435345716937405655305190657814877412786176000000000000000000000000000000000000000000000000000000000000000000000000000000000000001333735776850284124449081472890438

```

# Answer
> 2 votes
# Pyth - ~~9~~ 8 bytes

```
s^Rd.!Mh

```

Test Suite.

# Answer
> 2 votes
## JavaScript (ES7), 38 bytes

```
f=(n,a=1,i=0)=>i>n?0:a**a+f(n,a*++i,i)

```

# Answer
> 2 votes
# R, 42 ~~35~~ bytes

Now that I've read the question properly, I've put the sum in.

This requires the **gmp** (multiple precision arithmetic) library to be available. This allows for large numbers to be handled. Otherwise anything over 5 returns `INF`.

This is implemented as a unnamed function to avoid the `as.character` that would be required to output to STDOUT through `cat`

```
function(x)sum((i=gmp::factorialZ(0:x))^i)

```

Example run

```
> f <- function(x)sum((i=gmp::factorialZ(0:x))^i)
> f(5)
Big Integer ('bigz') :
[1] 3175042373780336892901667920556557182493442088021222004926225128381629943118937129098831435345716937405655305190657814877412786176000000000000000000000000000000000000000000000000000000000000000000000000000000000000001333735776850284124449081472890438
> f(6)
Big Integer ('bigz') :
[1] 190281878633201797429473437859705759836595323046380462211756876146775419721154680216391116383660154937824558291984804764687140715927099993629348072943551413397410741069111169123658220861477766905534108349401724389611558474171816216027733366046875815097164882588181826712426524007417126023680300953790645455254723360874298622143752208989152655091222094594342956890526202094068774356589887610542642450567071133028553816930267473112879050178461179814798008667622200592591542432361632955904924276854403585221477449385731481108378608652069211835448555831555820393949831627809528917004144455150642180845929102272754394116905511650997561389917179995442329297103257850695109383021080317204810134810158543814178231002423431556657737982683316707709406053569620116083909440177269311235173671447595521339849978144493268530780365729831790064477684808893338190825461650933123545889305523546630119181308584140916288912561260392366609493077363059677222110731132927863243720195975705161197786520981159422881575250362836779593393897664990291828935858671453835924398316498051705698128484688847592380831018330553151156822298060174230201841578757499203145955456593022852288527824268115043999037373974753999860179933517198889966353093307592136928730661270863274130109304971274296438682725017433937245229524959283895094220677649257613358344409711070780405579776000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003175042373780336892901667920556557182493442088021222004926225128381629943118937129098831435345716937405655305190657814877412786176000000000000000000000000000000000000000000000000000000000000000000000000000000000000001333735776850284124449081472890438

```

f(9) will runs pretty well, but fills up a number of pages. A few hundred or so and 2,017,528 digits. f(10) kills the session on my machine.

# Answer
> 2 votes
# Python 2, ~~73~~ 72 bytes

```
import math
lambda n,f=math.factorial:sum(f(i)**f(i)for i in range(n+1))

```

# Answer
> 2 votes
# PARI/GP, 19 bytes

```
n->sum(k=0,n,k!^k!)

```

# Answer
> 2 votes
# GameMaker Language, 97 bytes

Main function (52 bytes)

```
for(a=0;a<=argument0;a++)b+=power(f(a),f(a))return b

```

Function f (45 bytes)

```
a=argument0 if!a return 1else return a*f(a--)

```

# Answer
> 2 votes
# Dyalog APL, 10 bytes

```
(+/!*!)0,⍳

```

**How?**

range of input

`0,` preceded with 0

`!*!` apply `x! ^ x!`

`+/` sum

# Answer
> 2 votes
# Golfscript, 41 bytes

```
{.{,{1+}%{*}*}{;1}if}:f;~.,\+{.f\f?}%{+}*

```

Try it online!

# Answer
> 2 votes
# Thunno `+`, \\$ 7 \log\_{256}(96) \approx \\$ 5.76 bytes

```
RFDz.^S

```

Attempt This Online!

#### Explanation

```
RFDz.^S  # implicit input
         # + flag adds one
R        # range from 0
 F       # factorial of each
   z.    # for each number:
  D  ^   #  raise it to the power of itself
      S  # sum the resulting list
         # implicit output

```

# Answer
> 2 votes
# vemf, ~~3~~ 5 bytes

```
▲↕!┴^

```

## Explanation

```
▲↕    ' range [0, α)
   ┴  ' run this function:
    ^ '   exponentation
      ' with this for both inputs:
  !   '   factorial of each element in range

```

e.g. `3▲↕!┴^+`try it online

# Answer
> 1 votes
# Mathematica, 19 bytes

```
Sum[a!^a!,{a,0,#}]&

```

Anonymous function. Takes a number as input, and returns a number as output.

# Answer
> 1 votes
## Pyke, 11 bytes

```
hFSBD]1*B)s

```

Try it here!

```
hF          -  for i in range (0, input+1)
  SB        -     product(range(1, i+1)
    D]1*    -    [^]*^
        B   -   product(^)
          s - sum(^)

```

Fun fact: Pyke doesn't have a factorial built-in because `SB` is only 2 bytes!

# Answer
> 1 votes
## Haskell, 43 bytes

```
b n|f<-product[1..n]=f^f
a n=sum$b<$>[0..n]

```

Usage example: `a 3`-\> `46662`.

`b` calculates a single ultrafactorial and `a` sums all ultrafactorials from `0` to `n`.

# Answer
> 1 votes
# JavaScript (ES7), 44 bytes

```
g=n=>n?(f=a=>a?a*f(a-1):1)(n)**f(n)+g(n-1):1

```

# Answer
> 1 votes
# Python 2, 82 Bytes

```
x=input()
s=0
for z in range(x):
 t=1
 for i in range(z+1):t*=i+1
 s+=t**t
print s

```

# Answer
> 1 votes
# Wonder, 33 bytes

```
@sum(->@^ f\prod rng1#0f)rng0+1#0

```

Usage:

```
(@sum(->@^ f\prod rng1#0f)rng0+1#0)3

```

# Explanation

```
rng0+1#0

```

Create inclusive range from 0 to input.

```
->@^ f\prod rng1#0f

```

Map over the range with a function that 1) calculates the factorial of the item, 2) stores the result to `f`, and 3) calculates `f^f`.

```
sum

```

Sum.

# Answer
> 1 votes
# TI-Basic, 13 bytes

```
sum(seq(A!^A!,A,0,Ans

```

P.S. You can replace `sum(seq(` with `Σ(` if you have a newer operating system (no size change).

# Answer
> 1 votes
# Ruby 2, 41 bytes

```
->n{(1..n).reduce(s=1){|t,i|t+(s*=i)**s}}

```

# Answer
> 1 votes
# Husk, 7 bytes

```
→ṁo´^Πḣ

```

Try it online!

```
→          One plus
 ṁ         the sum of
     Π     x!
    ^      to the power of
   ´       itself
 ṁo        for each x in
      ḣ    the range from 1 to
           the input.

```

It would be slightly more correct to use `ṁo´^ΠΘḣ`, actually adding 0 into the range, but since 0!^0!=1^1=1, this works too.

# Answer
> 1 votes
# Whispers v3, <sup>~~77~~</sup> 69 bytes

```
> Input
> 0
>> L!
>> … 2 1 3
>> L*L
>> Each 5 4
>> ∑6
>> Output 7

```

Try it online!

Yet another 69 byte answer thanks to Leo.

# Answer
> 1 votes
# Pyt, 5 bytes

```
ř!ṖƩ⁺

```

Try it online!

```
ř           implicit input; řangify
 !          factorial
  Ṗ         raise n to the nth Ṗower
   Ʃ        Ʃum
    ⁺       increment

```

# Answer
> 1 votes
# Nibbles, 5.5 bytes

```
+~+.,$^;`*,

```

Attempt This Online!

*-0.5 byte thanks to Dominic van Essen*

```
+~+.,$^;`*,
+~          Add 1
  +         to the sum
   .        for each n in
    ,       range from 1 to
     $      input
        `*  of the product of
          , range from 1 to
            n
      ^     to the power of
       ;    itself

```

# Answer
> 1 votes
# Vyxal `s`, 4 bytes

```
ʀ¡:e

```

Try it Online!

```
ʀ  range [0, input]
¡  factorial (vectorizes)
:  duplicate list
e  exponentiate
s  sum

```

# Answer
> 1 votes
# Arturo, 29 bytes

```
$=>[∑map..0&=>[^<=∏1..&]]

```

Try it

# Answer
> 1 votes
# Stax, 10 bytes

```
Ç╔Ñst(jÖ3l

```

Run and debug it

This is PackedStax, which unpacks to the following 11 bytes:

```
R{|Fc#}m|+^

```

Run and debug it

```
R{    }m    # map over range 1..input
  |F        # push n!
    c       # dup
     #      # exponentiate
        |+  # sum
          ^ # increment (deals with 0 case)

```

# Answer
> 1 votes
# C (gcc), ~~71~~ 70 bytes

-1 byte thanks to @ceilingcat!

```
i,j,k;a(n){for(j=0;~n;--n,j+=pow(i,i))for(i=k=1;n/++k;)i*=k;return j;}

```

You can test it online here (Try It Online! seems to lack the `pow` function).

~~88~~ 87-byte solution without builtins:

```
i,j,k,e;a(n){for(j=0;~n;--n,j+=e){for(i=k=1;n/++k;)i*=k;for(e=k=i;--k;)e*=i;}return j;}

```

Try It Online!

# Answer
> 1 votes
# Python 3, 70 bytes

```
import math
x=lambda n,f=math.factorial:1if n==0else f(n)**f(n)+x(n-1)

```

Try it online!

# Answer
> 1 votes
# Thunno 2 `S`, 4 bytes

```
ĖwD*

```

Try it online!

#### Explanation

```
ĖwD*  # Implicit input
Ė     # Push [0..input]
 w    # Factorial of each
  D*  # To the power of itself
      # Implicit output of sum

```

# Answer
> 0 votes
# Brachylog, 12 bytes

```
y:{$!F:F^}a+

```

Try it online!

### Explanation

```
y                 The list [0, ..., Input]
 :{      }a       Apply the predicate below to each element of that list
           +      The output is the sum of the results

   $!F              F is the factorial of the input
      :F^           Output = F^F

```

# Answer
> 0 votes
# C#, 79 bytes with console output

```
n=>{int i=1,j=1;for(;i<=n;i++)j*=i;System.Console.Write(System.Math.Pow(j,j));}

```

# C#, 64 bytes as a return

```
n=>{int i=1,j=1;for(;i<=n;i++)j*=i;return System.Math.Pow(j,j);}

```

# Answer
> 0 votes
# Actually ~~11~~ 10 bytes

```
1+r`!;ⁿ`MΣ

```

**How it works**

```
Program takes implicit input, implicit print at EOF
1+          Add one to the input n+1
  r         Create a range (0,1,..,n)
   `   `    Create a function between the two `
    !       Factorialize the current stack item
     ;      Duplicate the current stack item
      ⁿ     Power a,b from the current stack item
         M  Map the function across the stack top item
          Σ Sum the stack together

```

# Answer
> 0 votes
## Racket 54 bytes

```
(for/sum((i(+ 1 n)))(let((t(factorial i)))(expt t t)))

```

Ungolfed:

```
#lang racket
(require math)

(define (f n)
  (for/sum ((i (+ 1 n)))
    (let ((t (factorial i)))
      (expt t t))))

```

Testing:

```
(f -1)
(f 0)
(f 1)
(f 2)
(f 3)

```

Output:

```
0
1
2
6
46662

```

# Answer
> 0 votes
# Japt, ~~8~~ 6 bytes

```
òÊx_pZ

```

Test it

---

## Explantion

Implicit input of integer `U`
`3`

```
ò

```

Create an array of integers from 0 to `U`, inclusive.
`[0,1,2,3]`

```
Ê

```

Get the factorial of each integer in the array.
`[1,1,2,6]`

```
_

```

Map over the array.

```
pZ

```

Raise each element (`p`) to the power of itself (`Z`).
`[1,1,4,46656]`

```
x

```

Reduce by addition and implicitly output the result.
`46662`

# Answer
> 0 votes
# APL (Dyalog), 11 bytes

```
+/(*⍨∘!0,⍳)

```

Try it online!

---

This function train is equivalent to `{+/*⍨!0,⍳⍵}`, which is a straight forward implementation

# Answer
> 0 votes
# Perl 6, 38 bytes

```
{[+] map {my \a=[*] 1..$_;a**a},0..$_}

```

Try it online!

# Answer
> 0 votes
# 05AB1E, 8 bytes

```
ƒN!N!m}O

```

Try it online!

# Answer
> 0 votes
# Factor \+ `math.factorials math.unicode`, 29 bytes

```
[ [0,b] [ n! dup ^ ] map Σ ]

```

Try it online!

```
  [0,b]                      ! range from 0 to input inclusive
        [          ] map     ! map over each element in the range
          n!                 ! factorial
             dup ^           ! raised to itself
                         Σ   ! sum

```

# Answer
> 0 votes
# Swift, ~~129~~ 106 bytes

```
import Darwin
var s={(0...$0).map{let x=Double($0<1 ?1:(1...$0).reduce(1,*))
return pow(x,x)}.reduce(0,+)}

```

Fatal-errors on `n < 0`, `inf` for `n >= 6`. Probably macOS-only due to needing to `import Darwin` to access the `pow(_:_:)` function. (Using `Darwin` instead of `Foundation` saved both 4 bytes and my sanity.)

When implementing the factorial, I had to hard-code the value for `0` in order to bypass `Fatal error: Range requires lowerBound <= upperBound`.

There's a space to the left of the `?` due to `1` not being optional. We don't need the space to the right.

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


title: The Work Day Countdown

text:
# Question
Title: The Work Day Countdown
I just had a genius idea for making the work-life easier - a countdown to a specific date which only counts workdays.

---

The basic task is to create a countdown to a specific date which only includes the workdays in the countdown.

As workday counts *Monday*, *Tuesday*, *Wednesday*, *Thursday* and *Friday*.

**The Input** should be a specific date in the "unofficial" European standard format `dd.MM.yyyy` and must be today or a day in the future.

**The Output** should only be the number of days left.

As it's the shortest code wins.

---

**Test case:**

```
  Today    |   Input    | Output
10.12.2018 | 17.12.2018 |    5
02.10.2018 | 16.10.2018 |   10

```

---

*If I missed a few things in the question, please forgive me - it's my first question :)*

**EDIT:**

* You can use `false` as output instead of `0` *\<- but it's not beautiful*
* No need for respecting DST

# Answer
## 05AB1E, ~~130~~ ~~128~~ ~~133~~ ~~131~~ ~~124~~ ~~123~~ ~~122~~ ~~121~~ 120 bytes

```
žežfžg)V0[Y`UD3‹©12*+>₂*T÷®Xα©т%D4÷®т÷©4÷®·()ćsO7%2@+Y`т‰0Kθ4ÖUD<i\28X+ë<7%É31α}‹iY¬>0ëY1¾ǝDÅsD12‹i>1ë\1Dǝ¤>2}}ǝVYI'.¡Q#

```

I'm out of my mind..

For the golfing language 05AB1E it doesn't matter at all whether the input is with `.` or `-`. However, 05AB1E doesn't have any builtins for Date objects or calculations. The only builtin regarding dates it has is today's year/month/day/hours/minutes/seconds/microseconds.

So because of that, almost all of the code you see are manual calculations to go to the next day, and calculating the day of the week.

+5 bytes due to a part I forgot in Zeller's formula (year-1 for months January and February)..
-1 byte thanks to @Grimmy, by changing \\$\left\lfloor{\frac{13(m+1)}{5}}\right\rfloor\\$ to \\$\left\lfloor{\frac{26(m+1)}{10}}\right\rfloor\\$ in the code, since 05AB1E has single-byte builtins for both `26` and `10` (being  and `T` respectively), as opposed to the 3 bytes of `13` and `5`.

Try it online or Try it online with an emulated self-specified date of 'today'.

### Explanation:

*Wall of text incoming.*

In general, the code follows the following pseudo-code:

```
1   Date currentDate = today;
2   Integer counter = 0;
3   Start an infinite loop:
4*    If(currentDate is NOT a Saturday and currentDate is NOT a Sunday):
5       Counter += 1;
6*    currentDate += 1; // Set currentDate to the next day in line
7     If(currentDate == parsed input-string):
8       Stop the infinite loop, and output the counter

```

1) `Date currentDate = today;` is this part of the 05AB1E program:

```
že          # Push today's day
  žf        # Push today's month
    žg      # Push today's year
      )     # Wrap them into a single list
       V    # Pop and store this list in variable `Y`

```

2) `Integer counter = 0;` and 3) `Start an infinite loop:` are straight-forward in the 05AB1E program:

```
0     # Push 0 to the stack
 [    # Start an infinite loop

```

4) `If(currentDate is NOT a Saturday and currentDate is NOT a Sunday):` is the first hard part with manual calculations. Since 05AB1E has no Date builtins, we'll have to calculate the *Day of the Week* manually.

The general formula to do this is:

$${\displaystyle h=\left(q+\left\lfloor{\frac{13(m+1)}{5}}\right\rfloor+K+\left\lfloor{\frac{K}{4}}\right\rfloor+\left\lfloor{\frac{J}{4}}\right\rfloor-2J\right){\bmod{7}}}$$

Where for the months March through December:

* \\$q\\$ is the \\$day\\$ of the month (`[1, 31]`)
* \\$m\\$ is the 1-indexed \\$month\\$ (`[3, 12]`)
* \\$K\\$ is the year of the century (\\$year \bmod 100\\$)
* \\$J\\$ is the 0-indexed century (\\$\left\lfloor {\frac {year}{100}}\right\rfloor\\$)

And for the months January and February:

* \\$q\\$ is the \\$day\\$ of the month (`[1, 31]`)
* \\$m\\$ is the 1-indexed \\$month + 12\\$ (`[13, 14]`)
* \\$K\\$ is the year of the century for the previous year (\\$(year - 1) \bmod 100\\$)
* \\$J\\$ is the 0-indexed century for the previous year (\\$\left\lfloor {\frac {year-1}{100}}\right\rfloor\\$)

Resulting in in the day of the week \\$h\\$, where 0 = Saturday, 1 = Sunday, ..., 6 = Friday.
Source: Zeller's congruence

We can see this in this part of the 05AB1E program:

```
Y             # Push variable `Y`
 `            # Push the day, month, and year to the stack
  U           # Pop and save the year in variable `X`
   D          # Duplicate the month
    3‹        # Check if the month is below 3 (Jan. / Feb.),
              # resulting in 1 or 0 for truthy/falsey respectively
      ©       # Store this in variable `®` (without popping)
       12*    # Multiply it by 12 (either 0 or 12)
          +   # And add it to the month
              # This first part was to make Jan. / Feb. 13 and 14

>             # Month + 1
 ₂*           # Multiplied by 26
   T÷         # Integer-divided by 10
®             # Push month<3 from variable `®` again
 Xα           # Take the absolute difference with the year
   ©          # Store this potentially modified year as new `®` (without popping)
    т%        # mYear modulo-100
D4÷           # mYear modulo-100, integer-divided by 4
®т÷©4÷        # mYear integer-divided by 100, and then integer-divided by 4
®·(           # mYear integer-divided by 100, doubled, and then made negative
)             # Wrap the entire stack into a list
 ć            # Extract the head (the counter variable that was also on the stack)
  s           # Swap so the calculated values above are as list at the top
   O          # Take the sum of this entire list
    7%        # And then take modulo-7 to complete the formula,
              # resulting in 0 for Saturday, 1 for Sunday, and [2, 6] for [Monday, Friday]

2@            # Check if the day is greater than or equal to 2 (so a working day)

```

5) `Counter += 1;` is straight-forward again:

```
     # The >=2 check with `2@` results in either 1 for truthy and 0 for falsey
+    # So just adding it to the counter variable is enough

```

6) `currentDate += 1; // Set currentDate to the next day in line` is again more complex, because we have to do it manually. So this will be expanded to the following pseudo-code:

```
a   Integer isLeapYear = ...;
b   Integer daysInCurrentMonth = currentDate.month == 2 ?
c                                 28 + isLeapYear
d                                :
e                                 31 - (currentDate.month - 1) % 7 % 2;
f   If(currentDate.day < daysInCurrentMonth):
g     nextDate.day += 1;
h   Else:
i     nextDate.day = 1;
j     If(currentDate.month < 12):
k       nextDate.month += 1;
l     Else:
m       nextDate.month = 1;
n       nextDate.year += 1;

```

Sources:
~~Algorithm for determining if a year is a leap year.~~ (EDIT: No longer relevant, since I use an alternative method to check leap years which saved 7 bytes.)
Algorithm for determining the number of days in a month.

6a) `Integer isLeapYear = ...;` is done like this in the 05AB1E program:

```
Y             # Push variable `Y`
 `            # Push the days, month and year to the stack
  т‰          # Divmod the year by 100
    0K        # Remove all items "00" (or 0 when the year is below 100)
      θ       # Pop the list, and leave the last item
       4Ö     # Check if this number is visible by 4
         U    # Pop and save the result in variable `X`

```

Also used in this 05AB1E answer of mine, so there some example years are added to illustrate the steps.

6b) `currentDate.month == 2 ?` and 6c) `28 + isLeapYear` are done like this:

```
D            # Duplicate the month that is now the top of the stack
 <           # Decrease it by 1
  i          # And if this is now 1 (thus February):
   \         #  Remove the duplicated month from the top of the stack
    28X+     #  Add 28 and variable `X` (the isLeapYear) together

```

6d) `:` and 6e) `31 - (currentDate.month - 1) % 7 % 2;` are done like this:

```
ë           # Else:
 <          #  Month - 1
  7%        #  Modulo-7
    É       #  Is odd (shortcut for %2)
     31     #  Push 31
       α    #  Absolute difference between both
}           # Close the if-else

```

6f) `If(currentDate.day < daysInCurrentMonth):` is done like this:

```
‹     # Check if the day that is still on the stack is smaller than the value calculated
 i    # And if it is:

```

6g) `nextDate.day += 1;` is done like this:

```
Y       # Push variable `Y`
 ¬      # Push its head, the days (without popping the list `Y`)
  >     # Day + 1
   0    # Push index 0

        # (This part is done after the if-else clauses to save bytes)
}}      # Close the if-else clauses
  ǝ     # Insert the day + 1 at index 0 in the list `Y`
   V    # Pop and store the updated list in variable `Y` again

```

6h) `Else:` and 6i) `nextDate.day = 1;` are then done like this:

```
ë        # Else:
 Y       #  Push variable `Y`
  1      #  Push a 1
   ¾     #  Push index 0
    ǝ    #  Insert 1 at index 0 (days part) in the list `Y`

```

6j) `If(currentDate.month < 12):`:

```
D           # Duplicate the list `Y`
 Ås         # Pop and push its middle (the month)
   D12‹     # Check if the month is below 12
       i    # And if it is:

```

6k) `nextDate.month += 1;`:

```
>       # Month + 1
 1      # Push index 1

        # (This part is done after the if-else clauses to save bytes)
}}      # Close the if-else clauses
  ǝ     # Insert the month + 1 at index 1 in the list `Y`
   V    # Pop and store the updated list in variable `Y` again

```

6l) `Else:`, 6m) `nextDate.month = 1;` and 6n) `nextDate.year += 1;` are then done like this:

```
ë        # Else:
 \       #  Delete the top item on the stack (the duplicated month)
  1      #  Push 1
   D     #  Push index 1 (with a Duplicate)
    ǝ    #  Insert 1 at index 1 (month part) in the list `Y`

 ¤       #  Push its tail, the year (without popping the list `Y`)
  >      #  Year + 1
   2     #  Index 2

         # (This part is done after the if-else clauses to save bytes)
}}       # Close the if-else clauses
  ǝ      # Insert the year + 1 at index 2 in the list `Y`
   V     # Pop and store the updated list in variable `Y` again

```

And finally at 7) `If(currentDate == parsed input-string):` and 8) `Stop the infinite loop, and output the counter`:

```
Y          # Push variable `Y`
 I         # Push the input
  '.¡     '# Split it on dots
     Q     # Check if the two lists are equal
      #    # And if they are equal: stop the infinite loop
           # (And output the top of the stack (the counter) implicitly)

```
> 21 votes

# Answer
# Excel 24 Bytes

Assumes input in Cell A1

```
=NETWORKDAYS(NOW()+1,A1)

```

Uses built-in function. Unfortunately the function includes both today and the end date. OP has since clarified to not count today, so I add one to NOW so as to not count today.

To address comments on format of number, again, this is Excel standard:
> 13 votes

# Answer
# , 76 bytes

Please also have a look at this 72 byte R answer that is also locale-independent.

```
sum(!grepl("S",weekdays(seq(Sys.Date(),as.Date(scan(,""),"%d.%m.%Y"),1))))+1

```

Try it online!

`weekdays` gives text days of week, so we count the days in the sequence between today and the input that do not contain `S`, and add one to the result.
> 11 votes

# Answer
# Java 10, ~~233~~ ~~232~~ 226 bytes

```
import java.util.*;d->{int r=0;var s=Calendar.getInstance();s.setTime(new Date());var e=s.getInstance();for(e.setTime(new java.text.SimpleDateFormat("dd.MM.yyyy").parse(d));!s.after(e);s.add(5,1))if(s.get(7)%7>1)r++;return r;}

```

Date always reminds me how verbose Java really is..

NOTE: There are now two shorter Java answers (below 175 bytes), one with smart use of deprecated methods from earlier Java versions by *@LukeStevens*, and one using the `java.time.LocalDate` that's new since Java 8 by *@OlivierGrégoire*.

Try it online.

**Explanation:**

```
import java.util.*;            // Required import for both Calendar and Date
d->{                           // Method with String parameter and integer return-type
  int r=0;                     //  Result-integer, starting at 0
  var s=Calendar.getInstance();//  Create a Calendar instance for the start-date
  s.setTime(new Date());       //  Set the start date to today
  var e=s.getInstance();       //  Create a Calendar instance for the end-date
  for(e.setTime(               //  Set the end date to:
        new java.text.SimpleDateFormat("dd.MM.yyyy")
                               //   Create a formatter for the "dd.MM.yyyy" format
         .parse(d));           //   And parse the input-String to a Date
      !s.after(e)              //  Loop as long as we haven't reached the end date yet
      ;                        //    After every iteration:
       s.add(5,1))             //     Increase the start-date by 1 day
    if(s.get(7)%7>1)           //   If the day of the week is NOT a Saturday or Sunday:
                               //   (SUNDAY = 1, MONDAY = 2, ..., SATURDAY = 7)
      r++;                     //    Increase the result-sum by 1
  return r;}                   //  Return the result-sum

```
> 8 votes

# Answer
# JavaScript (ES6), ~~116~~ 103 bytes

```
f=(d,n=+new Date)=>(D=new Date(n)).toJSON()<d.split`.`.reverse().join`-`&&(D.getDay()%6>0)+f(d,n+864e5)

```

Try it online!

### How?

A JavaScript timestamp is defined as the number of *milliseconds* elapsed since the UNIX epoch. The current timestamp is hold in the variable \\$n\\$.

At each iteration, we use \\$n\\$ to generate a date \\$D\\$ (as a JavaScript object). This date is converted to ISO 8601 format with the `.toJSON()` method:

```
*YYYY*-*MM*-*DD*T*hh*:*mm*:*ss.sss*Z
```

Since this string starts with `YYYY-MM-DD`, it is safe to perform a lexicographical comparison with another string in a similar format. This is why we want to convert the input string \\$d\\$ to `YYYY-MM-DD` rather than converting our computed date to the input string format `DD.MM.YYYY` (which cannot be sorted lexicographically):

```
d.split`.`.reverse().join`-`

```

Before each recursive call, we increment the final result if `D.getDay()` is neither \\$0\\$ (Sunday) nor \\$6\\$ (Saturday), i.e. if it's not congruent to \\$0\\$ modulo \\$6\\$:

```
(D.getDay() % 6 > 0) + f(d, n + 864e5)

```

We add \\$86,400,000\\$ milliseconds to \\$n\\$ to reach the next day.
> 7 votes

# Answer
# Wolfram Language (Mathematica), ~~64~~ 56 bytes

```
DayCount[Today,""<>#~StringTake~{{4,6},3,-4},"Weekday"]&

```

Try it online!

`DayCount[x,y,"Weekday"]` counts the number of weekdays between `x` and `y`.

The inputs `x` and `y` can be many things, including a fancy `DateObject` like the one returned by `Today`, or a string in the format (unfortunately) `mm.dd.yyyy`.

My previous attempt tried to turn the `dd.mm.yyyy` input into a `DateObject` by telling Mathematica how to parse it; the new solution simply rearranges the string to put day and month in the order Mathematica expects.

It's worth noting that the 28-byte solution `DayCount[Today,#,"Weekday"]&` not only works perfectly for a month-day-year input format, but also correctly handles *unambiguous* day-month-year inputs such as `31.12.2018`, which couldn't possibly mean "the 12th day of the 31st month". So it's correct more than 60% of the time :)
> 6 votes

# Answer
# MATL, 24 bytes

```
46tQZt24&YO:Z':X-9XO83-z

```

Try it online!

> I don't want to have any input format so that specific code golf languages got a big advantage

You half succeeded :-)

### Explanation

```
46      % Push 46 (ASCII for '.')
tQ      % Duplicate, add 1: gives 47 (ASCII for '/')
Zt      % Implicit input. Replace '.' by '/' in the input string
24&YO   % Convert string with date format 24 ('dd/mm/yyyy') to serial date number.
        % This is an integer representing day starting at Jan-1-0000
:       % Inclusive range from 1 to that
Z'      % Push current date and time as a serial number. Integer part is day;
        % decimal part represents time of the day
:       % Inclusive range from 1 to that
X-      % Set difference. Gives serial numbers of days after today, up to input
9XO     % Convert each number to date format 9, which is a letter for each day
        % of the week: 'M', 'T', 'W', 'T', ' F', 'S', 'S'
83-     % Subtract 83 (ASCII for 'S')
z       % Number of nonzeros. Implicit display

```
> 6 votes

# Answer
# Perl 6, 61 bytes

```
{+grep 6>*.day-of-week,Date.today^..Date.new(|[R,] m:g/\d+/)}

```

Try it online!
> 5 votes

# Answer
# Java (OpenJDK 8), 174 166 165 bytes

With a bit of inspiration from Kevin's answer and a good ol' trawl through the deprecated Date API, I've managed to get a more succinct Java solution.

*-8 bytes thanks to Kevin's inventive regex date parsing*

*-1 bytes thanks to Nevay's clever bitwise operation*

```
import java.util.*;d->{long r=0,s=new Date().getTime(),e=Date.parse(d.replaceAll("(..).(..).","$2/$1/"));for(;s<=e;s+=864e5)r-=-new Date(s).getDay()%6>>-1;return r;}

```

Try it online!

**Explanation**

```
import java.util.*;                         // Required import for Date
long r=0,                                   // Initialise result variable
     s=new Date().getTime(),                // Current date in millis
     e=Date.parse(
         d.replaceAll("(..).(..).","$2/$1/")// Use regex to convert to MM/dd/yyyy
     );                                     // Parse date arg using deprecated API
for(;s<=e;                                  // Loop while current millis are less than date arg (e.g. date is before)
    s+=864e5)                               // Add 86400000 ms to current date (equiv of 1 day)
    r-=-new Date(s).getDay()%6>>-1;        // If day is Sunday (0) or Saturday (6) don't increment, else add 1
return r;                                   // When loop finished return result

```
> 5 votes

# Answer
# R, 72 chars

A variation on the answer provided by @ngm which avoids the grepl to save a few characters and works in non-English locales.

`sum(strftime(seq(Sys.Date(),as.Date(scan(,""),"%d.%m.%Y"),1),'%u')<6)+1`
> 5 votes

# Answer
# Red, 72 bytes

```
func[a][b: now/date s: 0 until[if b/weekday < 6[s: s + 1]a < b: b + 1]s]

```

Try it online!

Takes the date in format dd-mm-yyyy, for example 31-10-2018 (also works with 10-Oct-2018)

## Strict input:

# Red, 97 bytes

```
func[a][a: do replace/all a".""-"b: now/date s: 0 until[if b/weekday < 6[s: s + 1]a < b: b + 1]s]

```

Try it online!

## Bonus:

Returns a list of the dates/weekdays of the working days up to the given date:

# Red, 235 bytes

```
f: func [ a ] [
    b: now/date
    d: system/locale/days
    collect [
        until [
            if b/weekday < 6 [
                keep/only reduce [ b ":" d/(b/weekday) ]
            ]
            a < b: b + 1
        ]
    ]
]

```

Try it online!
> 4 votes

# Answer
# JavaScript, ~~87~~ 85 bytes

Returns `false` for `0`.

```
s=>([d,m,y]=s.split`.`,g=_=>new Date<(x=new Date(y,~-m,d--))&&(x.getDay()%6>0)+g())()

```

Try it online or check the next 31 days
> 4 votes

# Answer
# JavaScript (Node.js), ~~168~~ ~~160~~ ~~139~~ 133 bytes

*35 bytes less thanks to Quintec and Kevin Cruijssen*

```
D=>{var i=D.split('.'),n=0;for(var d=new Date();d<=new Date(i[2],i[1]-1,i[0]);d.setDate(d.getDate()+1))n+=-~d.getDay()%7>1;return n;}

```

Try it online!

```
D=>{
  var i=D.split('.'),                 // Splits the date string by .
      n=0;                            // Counter variable
  for(var d=new Date();               // For the actual date
      d<=new Date(i[2],i[1]-1,i[0]);      // As long as the date is less or equal the requested date
      d.setDate(d.getDate()+1))           // Count the date one up
    n+=-~d.getDay()%7>1;                // If the date is not a Sunday or Saturday
  return n;                           // Return the counter variable
}

```
> 3 votes

# Answer
# Python 2, ~~163~~ ~~156~~ ~~149~~ 147 bytes

```
lambda s:sum((date.today()+timedelta(x)).weekday()<5for x in range((date(*map(int,(s.split(".")[::-1])))-date.today()).days))
from datetime import*

```

Try it online!

-7 with thanks to @mypetlion

-7 more with thanks to @ovs

+30 due to the very restrictive input format which I only noticed just before I posted my previous code which took input as e.g. `(2018,11,1)` :-(
> 3 votes

# Answer
# Python3 & Numpy, 96 bytes

I couldn't get smaller than the boring pre-made solution...

```
from numpy import*
d=datetime64
lambda s:busday_count(d('today'),d(f'{s[6:]}-{s[3:5]}-{s[:2]}'))
```

Try it online!
> 3 votes

# Answer
# Java (JDK 10), 171 bytes

```
s->{int c=0;for(var t=java.time.LocalDate.now();!t.parse(s.replaceAll("(..).(..).(.*)","$3-$2-$1")).equals(t);t=t.plusDays(1))c-=t.getDayOfWeek().getValue()/6-1;return c;}

```

Try it online!

## Credits
> 3 votes

# Answer
# PowerShell, ~~107~~ 99 bytes

*-8 bytes thanks to mazzy*

```
$d,$m,$y=$args-split'\.';for($a=date;$a-lt(date "$y-$m-$d");$a=$a|% *ys 1){$o+=($a|% D*k)-in1..5}$o

```

Try it online!

Performs a regex `-split` on the input `$args`, stores the values into `$d`ays, `$m`onths, and `$y`ears, respectively. Then, enters a `for` loop, initializing `$a` to today's date. The loop continues while `$a` is `-l`ess`t`han our input target date. Each iteration we're adding `1` da`ys` to `$a`, and checking whether the current `D*k` (short for `DayOfWeek`) is in the range `1..5` (i.e., Monday to Friday). That Boolean result is accumulated into `$o` and once we're out of the loop that value is left on the pipeline and output is implicit.
> 2 votes

# Answer
# Python 2, ~~147~~ ~~143~~ ~~141~~ 140 bytes

```
from datetime import*
lambda e,s=date.today():sum((s+timedelta(x+1)).weekday()<5for x in range((date(*map(int,e.split(".")[::-1]))-s).days))

```

Try it online!

Takes a string, e, which represents the end date in the format "dd.MM.YYYY". Optionally also takes the start date, but this is expected to be a datetime.date.

The start date, s, is defaulted to today's date as a datetime.date object in order to disregard time. The end time is parsed into a datetime.datetime object then converted to a date, since datetime.date objects do not have a parse method and datetimes cannot be added to/subtracted from dates. Iterates through every day in (start, end\] and adds 1 to the total if its weekday number is \< 5. (\[0-4\] are \[Mon-Fri\], \[5-6\] are \[Sat-Sun\]).

Datetime parsing is the worst, you guys.

EDIT: Stole ElPedro's map(int,thing) trick to save 4 bytes.

EDIT 2: ELECTRIC BOOGALOO: Saved 2 bytes by making it an anonymous function. (Thanks Aaron!)

EDIT 3: xrange -\> range. (Thanks again Aaron!)
> 2 votes

# Answer
# PHP (with Carbon), 107 bytes

```
function a($d){return Carbon\Carbon::parse($d)->diffInDaysFiltered(function($e){return!$e->isWeekend();});}

```
> 2 votes

# Answer
# K4, 40 bytes

**Solution:**

```
{+/1<.q.mod[d+!(."."/:|"."\:x)-d:.z.d]7}

```

**Explanation:**

Calculate the difference between the dates, use modulo 7 to ignore weekends, sum up.

```
{+/1<.q.mod[d+!(."."/:|"."\:x)-d:.z.d]7} / the solution
     .q.mod[                         ]7  / modulo with 7
                                 .z.d    / UTC date
                               d:        / save as d
                              -          / subtract from
               (             )           / do this together
                       "."\:x            / split input on "."
                      |                  / reverse
                 "."/:                   / join back with "."
                .                        / take the value
              !                          / range 0..the difference
            d+                           / add today's date to range
   1<                                    / is 1 less than the modulo (ie is this mon-fri)?
 +/                                      / sum up

```

**Notes:**

* same byte alternative to the date parsing: `"D"$,/|"."\:x`
> 2 votes

# Answer
# PHP, 66 bytes

```
for($t=time();$t<strtotime($argn);)$r+=date(N,$t+=86400)<6;echo$r;

```

empty output for `0`; insert `+` between `echo` and `$r` to fix.

Run as pipe with `-nr` or try it online.

---

60 bytes with unary output:

```
for($t=time();$t<strtotime($argn);)echo date(N,$t+=86400)<6;

```
> 2 votes

# Answer
# C (clang), ~~209~~ ~~208~~ 205 bytes

Compiler flags `-DU=u=localtime(&b)` `-DW=tm_wday` `-DY=tm_year` `-DT=tm_yday` (52 bytes).

```
#import<time.h>
i;f(char*a){long b;struct tm t,*u;time(&b);U;strptime(a,"%d.%m.%Y",&t);for(i=0;u->T^t.T|u->Y^t.Y;u->W&&u->W^6&&i++,b+=86400,U);return i;}

```

Try it online!

-1 byte thanks to @JonathanFrech
> 1 votes

# Answer
# IBM/Lotus Notes Formula - 99 bytes

```
d:=i;c:=0;@While(d>@Today;@Set("c";c+@If(@Weekday(d)=1:7;0;1));@Set("d";@Adjust(d;0;0;-1;0;0;0)));c

```

Takes input from a date/time field `i`. The input format of `i` is set to `.` separated so there is no need to convert the input. Notes can take a date input with any separator as long as you tell it before what it is going to be (hope that's not cheating!). Formula is in computed numeric field `o` on the same form.

Interesting aside: Ever since `@For` and `@While` were introduced into the Formula language in (I think) R6 by the great Damien Katz the only use I have found for them is code golfing. I have never used them in a production app.

There is no TIO available for formula so here is a screenshot taken on 02.10.2018:
> 1 votes

# Answer
# q, 52 79 bytes

```
{x:"D"$"."sv reverse"."vs x;i:0;while[x-.z.d;$[2>x mod 7;x-:1;[i+:1;x-:1]]];:i}

```

in q, each date has an underlying integer value, based on how many days have passed since the start of the millenium. Applying 'mod 7' to this, you get unique values for each day of the week (0 for Saturday, 6 for Friday). So when 2 \> x mod 7, don't increment the counter, to avoid counting weekends.

EDIT: Missed strict date format, editing

EDIT2: Included
> 1 votes

# Answer
# Ruby, 81 bytes

```
->e{require'date';(Date.today...Date.strptime(e,'%d.%m.%Y')).count{|d|6>d.cwday}}

```

Try it online!
> 1 votes

# Answer
# Scala, 251 bytes

Port of @Olivier Grégoire's Java answer in Scala.

---

Golfed version. Try it online!

```
def c(d:String):Int={var r=0;val s=Calendar.getInstance;s.setTime(new Date);val e=Calendar.getInstance;e.setTime(new SimpleDateFormat("dd.MM.yyyy").parse(d));while(!(s after e)){if(s.get(Calendar.DAY_OF_WEEK)%7>1)r+=1;s.add(Calendar.DAY_OF_YEAR,1)};r}

```

Ungolfed version. Try it online!

```
import java.util._
import java.text.SimpleDateFormat

object Main extends App {
  trait N {
    @throws[Exception]
    def c(d: String): Int
  }

  val n: N = new N {
    def c(d: String): Int = {
      var r = 0
      val s = Calendar.getInstance()
      s.setTime(new Date())
      val e = Calendar.getInstance()
      e.setTime(new SimpleDateFormat("dd.MM.yyyy").parse(d))
      while (!s.after(e)) {
        if (s.get(Calendar.DAY_OF_WEEK) % 7 > 1) r += 1
        s.add(Calendar.DAY_OF_YEAR, 1)
      }
      r
    }
  }

  println(n.c("16.10.2018"))
  println(n.c("01.01.2100"))
}

```
> 1 votes

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


title: Product of Divisors

text:
# Question
Title: Product of Divisors
# Challenge

Given a positive integer, return the product of its divisors, including itself.

This is sequence A007955 in the OEIS.

# Test Cases

```
1: 1
2: 2
3: 3
4: 8
5: 5
6: 36
7: 7
8: 64
9: 27
10: 100
12: 1728
14: 196
24: 331776
25: 125
28: 21952
30: 810000

```

# Scoring

This is , so the shortest answer in each language wins!

# Answer
> 14 votes
# 05AB1E, 2 bytes

```
ÑP

```

Try it online!

**Explanation**

```
Ñ    # divisors
 P   # product

```

# Answer
> 8 votes
# Japt, 3 bytes

```
â ×

```

Try it online!

## Explanation

```
â ×  // implicit integer input

â    // get integer divisors
  ×  // get product of array

```

# Answer
> 6 votes
# Python 3, ~~42~~ 41 bytes

Saved 1 byte thanks to Leaky Nun!

```
f=lambda i,k=1:k>i or k**(i%k<1)*f(i,k+1)

```

Try it online!

# Answer
> 5 votes
# Jelly, 3 bytes

```
ÆDP

```

Try it online!

# Answer
> 5 votes
# MATL, 3 bytes

```
Z\p

```

Try it online!

# Answer
> 4 votes
# Haskell, 35 34 bytes

*-1 thanks to ovs*

```
f n=product[x|x<-[2..n],n`mod`x<1]

```

Try it online!

# Answer
> 4 votes
## Alice, 12 bytes

```
/o
\i@/Bdt&*

```

Try it online!

### Explanation

This is just the regular framework for decimal I/O:

```
/o
\i@/...

```

Then the program is:

```
B    Get all divisors of the input.
dt   Get the stack depth minus 1.
&*   Multiply the top two stack elements that many times, folding multiplication
     over the stack.

```

# Answer
> 4 votes
# Factor, 43 bytes

```
[ dup [1,b] [ dupd divisor? ] count 2 / ^ ]

```

Try it online!

Uses the formula `n^((number of divisors of n)/2)`.

Usually `mod 0 =` (7 bytes) is shorter than `divisor?` (8 bytes), but the latter is used here to auto-load `math.functions` to disambiguate `^` (which happens to appear in a regex lib). Auto-use is weird. The unambiguous alternative to `^` exists (`fpow`), but it's longer.

```
[                ! anonymous lambda
  dup [1,b]      ! ( n {1..n} )
  [ ... ] count  ! count the elements that satisfy the predicate...
    dupd         !   ( n i -- n n i )
    divisor?     !   ( n ? ) tests if i is a divisor of n
  2 / ^          ! halve the divisor count and raise n to the power
]

```

---

# Factor, 45 bytes

```
USE: math.primes.factors
[ divisors product ]

```

Try it online!

Uses `divisors` built-in, but obviously the library import is expensive.

# Answer
> 3 votes
# Pyth, 6 bytes

```
*Fs{yP

```

Test suite.

# Answer
> 3 votes
# Neim, 2 bytes

```

```

Try it online!

# Answer
> 3 votes
# , 28 bytes

```
v=scan():1;prod(v[!v[1]%%v])

```

Try it online!

# Answer
> 3 votes
# x86-64 Machine Code, 26 bytes

```
31 C9 8D 71 01 89 F8 FF C1 99 F7 F9 85 D2 75 03 0F AF F1 39 F9 7C EE 89 F0 C3

```

The above code defines a function that takes a single parameter (the input value, a positive integer) in `EDI` (following the System V AMD64 calling convention used on Gnu/Unix), and returns a single result (the product of divisors) in `EAX`.

Internally, it computes the product of divisors using an (extremely inefficient) iterative algorithm, similar to pizzapants184's C submission. Basically, it uses a counter to loop through *all* of the values between 1 and the input value, checking to see if the current counter value is a divisor of the input. If so, it multiplies that into the running total product.

**Ungolfed assembly language mnemonics:**

```
; Parameter is passed in EDI (a positive integer)
ComputeProductOfDivisors:
   xor   ecx, ecx        ; ECX <= 0  (our counter)
   lea   esi, [rcx + 1]  ; ESI <= 1  (our running total)
.CheckCounter:
   mov   eax, edi        ; put input value (parameter) in EAX
   inc   ecx             ; increment counter
   cdq                   ; sign-extend EAX to EDX:EAX
   idiv  ecx             ; divide EDX:EAX by ECX
   test  edx, edx        ; check the remainder to see if divided evenly
   jnz   .SkipThisOne    ; if remainder!=0, skip the next instruction
   imul  esi, ecx        ; if remainder==0, multiply running total by counter
.SkipThisOne:
   cmp   ecx, edi        ; are we done yet? compare counter to input value
   jl    .CheckCounter   ; if counter hasn't yet reached input value, keep looping

   mov   eax, esi        ; put our running total in EAX so it gets returned
   ret

```

The fact that the `IDIV` instruction uses hard-coded operands for the dividend cramps my style a bit, but I think this is pretty good for a language that has no built-ins but basic arithmetic and conditional branches!

# Answer
> 3 votes
# Vyxal, 2 bytes

Explanation:

```
K  # Gets the divisors of a number
 Π # Product of array

```

Try it Online!

# Answer
> 2 votes
# TI-Basic (TI-84 Plus CE), 24 bytes

```
Prompt X
1
For(A,1,X
If not(remainder(X,A
AAns
End

```

Full program: prompts user for input; returns output in `Ans`, a special variable that (basically) stores the value of the latest value calculated.

Explanation:

```
Prompt X             # 3 bytes, Prompt user for input, store in X
1                    # 2 bytes, store 1 in Ans for use later
For(A,1,X            # 7 bytes, for each value of A from 1 to X
If not(remainder(X,A # 8 bytes, If X is divisible by A...
AAns                 # 3 bytes, ...store (A * Ans) in Ans
End                  # 1 byte, end For( loop

```

# Answer
> 2 votes
# C (gcc), ~~52~~ 48 bytes

```
p,a;f(x){for(p=1,a=x;a;a--)p*=x%a?1:a;return p;}

```

-4 bytes thanks to Cody Gray

A function that takes in an integer and returns the product of it's divisors.

Try it online!

Ungolfed:

```
int proddiv(int input) {
    int total = 1, loopvar;
    for(loopvar = input; loopvar > 0; --loopvar) {
    // for loopvar from input down to 1...
        total *= (input % loopvar) ? 1 : loopvar;
        // ...If the loopvar is a divisor of the input, multiply the total by loopvar;
    }
    return total;
}

```

# Answer
> 2 votes
# JavaScript (ES7), 32 bytes

```
n=>g=(i=n)=>i?i**!(n%i)*g(i-1):1

```

Saved a couple of bytes by borrowing Leaky's tip on musicman's Python solution.

---

## Try it

```
o.innerText=(f=
n=>g=(i=n)=>i?i**!(n%i)*g(i-1):1
)(i.value=1)();oninput=_=>o.innerText=f(+i.value)()
```

```
<input id=i type=number><pre id=o>
```

---

## Alternative (ES6), 32 bytes

```
n=>g=(i=n)=>i?(n%i?1:i)*g(i-1):1

```

# Answer
> 2 votes
# TI-Basic, ~~24~~ ~~14~~ 13 bytes

Saved 1 byte thanks to lirtosiast

```
:√(Ans^sum(not(fPart(Ans/randIntNoRep(1,Ans

```

# Answer
> 2 votes
# Shakespeare Programming Language, 353 bytes

```
.
Ajax,.
Puck,.
Page,.
Act I:.
Scene I:.
[Enter Ajax and Puck]
Ajax:
You cat
Puck:
Listen to thy heart
[Exit Ajax]
[Enter Page]
Scene II:.
Puck:
You sum you cat
Page:
Is Ajax nicer I?If so, is remainder of the quotient Ajax I nicer zero?If not, you product you I.Is Ajax nicer I?If so, let us return to scene II
Scene III:.
Page:
Open thy heart
[Exeunt]

```

Ungolfed version:

```
The Tragedy of the Product of a Moor's Factors in Venice.

Othello, a numerical man.
Desdemona, a product of his imagination.
Brabantio, a senator, possibly in charge of one Othello's factories.

Act I: In which tragedy occurs.

Scene I: Wherein Othello and Desdemona have an enlightened discussion.

[Enter Othello and Desdemona]

Othello:
  Thou art an angel!

Desdemona:
  Listen to thy heart.

[Exit Othello]
[Enter Brabantio]

Scene II: Wherein Brabantio expresses his internal monologue to Desdemona.

Desdemona:
  Thou art the sum of thyself and the wind!

Brabantio:
  Is Othello jollier than me?
  If so, is the remainder of the quotient of Othello and I better than nothing?
  If not, thou art the product of thyself and me.
  IS Othello jollier than me?
  If so, let us return to scene II!

Scene III: An Epilogue.

Brabantio:
  Open thy heart!

[Exeunt]

```

I'm using this SPL compiler to run the program.

Run with:

```
$ python splc.py product-of-divisors.spl > product-of-divisors.c
$ gcc product-of-divisors.c -o pod.exe
$ echo 30 | ./pod
810000

```

# Answer
> 2 votes
# RProgN 2, 2 bytes

```
ƒ*

```

Another language with built ins for `divisors` and `product`.

Try it online!

# Answer
> 2 votes
# APL (Dyalog Unicode), 7 bytes

-1 byte thanks to @rak1507.

```
f←×/∘∪⊢∨⍳

```

Try it online!

# Answer
> 2 votes
# Go, ~~65~~ 64 bytes

```
func p(n int)int{p,i:=1,1
for;i<=n;i++{if n%i<1{p*=i}}
return p}

```

Attempt This Online!

### Ungolfed

* -1 swapping `==0` for `<1` (@Steffan)

```
func product(s []int) int {
	p := 1
	for _,e := range s {
		p *= e
	}
	return p
}
func divisors(n int) (d []int) {
	for i := 1; i <= n; i++ {
		if n % i == 0 {
			d = append(d, i)
		}
	}
	return d
}

```

Attempt This Online!

# Answer
> 1 votes
# QBIC, 22 bytes

```
[:|~b/a=b'\`a|q=q*a}?q

```

## Explanation

```
[:|           FOR a  = 1; a <= input (b); a++
 b/a=b'\`a    'a' is a proper divisor if integer division == float division
~         |   IF that's true
q=q*a         THEN multiply running total q (starts as 1) by that divsor
}             NEXT
?q            Print q

```

# Answer
> 1 votes
# Python 2, ~~52~~ 50 bytes

* Thanks @ovs for 2 bytes: `m*=n%i>0 or i`

```
i=n=input()
m=1
while i:m*=n%i>0 or i;i-=1
print m

```

Try it online!

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

```
n->n^(numdiv(n)/2)

```

Try it online!

# Answer
> 1 votes
# Octave, 27 bytes

```
@(n)prod(find(~mod(n,1:n)))

```

This defines an anonymous function.

Try it online!

# Answer
> 1 votes
# PHP, 45 bytes

```
for($p=1;$d++<$argn;)$argn%$d?:$p*=$d;echo$p;

```

Try it online!

# Answer
> 1 votes
# Mathematica, 17 bytes

for those who can't view deleted answers (DavidC's answer), this is the code in Mathematica with the help of @MartinEnder

```
1##&@@Divisors@#&

```

# Answer
> 1 votes
## Python 3, 45 bytes

`lambda _:_**(sum(_%-~i<1for i in range(_))/2)`

Let `x` be a number. Both `y` and `z` will be divisors of `x` if `y * z = x`. Therefore, `y = x / z`. Let's say a number `d` has 6 divisiors, due to this observation the divisors will be `a`, `b`, `c`, `d / a`, `d / b`, `d / b`. If we multiply all these numbers (the point of the puzzle), we obtain `d * d * d = d ^ 3`. In general, for `e` with a number of `f` divisors, the product of said divisors will be `e ^ (f / 2)`, which is what the lambda does.

Try it online!

# Answer
> 1 votes
# Java (OpenJDK 8), ~~52~~ 51 bytes

```
n->{int r=n,d=0;for(;++d<n;)r*=n%d<1?d:1;return r;}

```

Try it online!

Thanks LeakyNun for saving 1 byte!

# Answer
> 1 votes
# MY, 4 bytes

Hex:

```
1A 3A 54 27

```

Explanation:

```
1A - Input as an integer
3A - Factors
54 - Product
27 - Output (with newline)

```

# Answer
> 1 votes
# Ruby, 36 bytes

```
->r{eval (1..r).select{|c|r%c<1}*?*}

```

Try it online!

# Answer
> 1 votes
# Excel VBA, 48 Bytes

Anonymous VBE immediate window function that takes input from range `[A1]` and outputs to the VBE immediate window

```
p=1:For i=1To[A1]:p=p*IIf([A1]mod i,1,i):Next:?p

```

# Answer
> 1 votes
# PowerShell Core, ~~41~~ 40 bytes

```
param($a)(1..$a|?{!($a%$_)})-join'*'|iex

```

-1 byte thanks to mazzy!

Try it online!

# Answer
> 1 votes
# x86-64 machine code, 23 bytes

Hexdump:

```
44 8b c1 6a 01 41 8b c0 99 f7 f9 85 d2 75 04 5a
f7 ea 50 e2 f0 58 c3

```

Uses the Microsoft calling convention - input in `ecx`, output in `eax`. It only supports 32-bit intermediate and final results, to make the code shorter.

Assembly code (can be assembled by `ml64`):

```
.CODE
my  PROC
        mov r8d, ecx;   // r8 = input number
        push 1;         // number on stack = product
    myloop:
        mov eax, r8d;   // prepare divisor
        cdq;            // in edx:eax
        idiv ecx;       // divide
        test edx, edx;  // check remainder
        jnz myskip;     // nonzero? - not a divisor
        pop rdx;        // get product from stack
        imul edx;       // multiply
        push rax;       // save product on stack
    myskip:
        loop myloop;    // check next number, down to 0
        pop rax;        // restore stack to proper position
        ret;            // return
my    ENDP
END

```

I used x64 only for its calling convention - so I would not have to save and restore a general-purpose register - x64 calling conventions permit clobbering `r8` and `r9`.

I used a variant of `imul` with implicit input and output in `eax` \- it has a shorter encoding (2 bytes), and doesn't require `mov` to return the result from the function at the end. So it actually multiplies the quotients, not the divisors; the final result remains correct.

Disassembly (to see instruction sizes):

```
00007FF7F91E1870 44 8B C1             mov         r8d,ecx
00007FF7F91E1873 6A 01                push        1
    myloop:
00007FF7F91E1875 41 8B C0             mov         eax,r8d
00007FF7F91E1878 99                   cdq
00007FF7F91E1879 F7 F9                idiv        eax,ecx
00007FF7F91E187B 85 D2                test        edx,edx
00007FF7F91E187D 75 04                jne         myloop+0Eh (07FF7F91E1883h)
00007FF7F91E187F 5A                   pop         rdx
00007FF7F91E1880 F7 EA                imul        edx
00007FF7F91E1882 50                   push        rax
    myskip:
00007FF7F91E1883 E2 F0                loop        myloop (07FF7F91E1875h)
00007FF7F91E1885 58                   pop         rax
00007FF7F91E1886 C3                   ret

```

# Answer
> 1 votes
# Husk, 2 bytes

```
ΠḊ

```

Try it online!

builtins.

# Answer
> 1 votes
# Fig, \\$3\log\_{256}(96)\approx\\$ 2.469 bytes

```
*rk

```

Try it online!

Multiplication analog of the addition version.

# Answer
> 1 votes
# Prolog (SWI), 60 bytes

```
A+N+S:-A>0,A-1+N+Q,(N mod A<1,S is Q*A;S=Q);S=1.
N+S:-N+N+S.

```

Try it online!

# Answer
> 1 votes
# Pyt, 2 bytes

```
ðΠ

```

Try it online!

```
ð       implicit input; get list of divisors
 Π      product of list; implicit print

```

# Answer
> 1 votes
# Thunno 2, 2 bytes

```
Fp

```

Try it online!

#### Explanation

```
Fp  # Implicit input
F   # Factors
 p  # Product
    # Implicit output

```

# Answer
> 0 votes
# Perl 6, 22 bytes

```
{[*] grep $_%%*,1..$_}

```

Try it online!

# Answer
> 0 votes
# J, 19 bytes

```
*/}.I.(=<.)(%i.@>:)

```

Explanation coming later...

Try it online!

# Answer
> 0 votes
# Fortran 95, 88 bytes

```
function l(k)
n=0
l=1
do while(n<k)
n=n+1
if(MODULO(k,n)==0)then
l=l*n
end if
end do
end

```

Try it online!

**Ungolfed:**

```
integer function l(k)
    implicit none
    integer :: n, k

    n=0
    l=1
    do while (n<k)
        n=n+1
        if (MODULO(k,n) == 0) then
            l=l*n
        end if
    end do

end function l

```

# Answer
> 0 votes
# Axiom, 23 bytes

```
h(x)==x^(#divisors x/2)

```

This is a translation in Axiom of alephalpha solution

# Answer
> 0 votes
# Arn, 3 bytes

```
Þ┤â

```

Try it!

# Explained

Unpacked: `*\*.`

`*\` fold with multiplication

`*.` a list of factors of the input

# Answer
> 0 votes
# Julia, 27 bytes

```
f(x,y=1:x)=prod(y[x.%y.<1])

```

Try it online!

# Answer
> 0 votes
# MathGolf, 3 bytes

```
─ε*

```

Try it online.

**Explanation:**

```
─    # Get a list of divisors of the (implicit) input-integer
 ε   # Reduce this list by:
  *  #  Subtracting
     # (after which the entire stack joined together is output implicitly as result)

```

# Answer
> 0 votes
# SageMath, 24 bytes

```
f=compose(prod,divisors)

```

Straightforward and direct. Is there a shorter way to do it in Sage?

# Answer
> 0 votes
# Perl 5 `-ap`, 31 bytes

```
map$.*="@F"%$_?1:$_,2..$_;$_=$.

```

Try it online!

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