title: Do you win a Numeric Mahjong?

text:
# Question
Title: Do you win a Numeric Mahjong?
## Background

Numeric Mahjong is a hypothetical variation of Japanese Mahjong, played with nonnegative integers instead of Mahjong tiles. Given a list of nonnegative integers, it is a *winning hand* if it satisfies the following:

* its length is \\$3n+2\\$ for some nonnegative integer \\$n\\$, and
* it can be partitioned into \\$n\\$ triples and a pair so that
    + each triple consists of three identical numbers \\$(x,x,x)\\$ or three consecutive numbers \\$(x,x+1,x+2)\\$, and
    + the pair consists of two identical numbers \\$(x,x)\\$.

## Challenge

Write a program or function that tests if a given a list of nonnegative integers is a winning hand in Numeric Mahjong. As this is a challenge, **your source code** (when converted to a list of integers) **must be a winning hand.** For example, `print(1)` is not a valid answer even if it implements the task, but the following may be:

```
print(1)###*11ios

```

whose ASCII values in sorted order is `[35, 35, 35, 40, 41, 42, 49, 49, 49, 105, 105, 110, 111, 112, 114, 115, 116]`, which can be partitioned to five triples `[35, 35, 35], [40, 41, 42], [49, 49, 49], [110, 111, 112], [114, 115, 116]` and a pair `[105, 105]`.

When converting the source code to integers, you may choose between

* Unicode codepoints of each char (when the source code is a sequence of Unicode characters),
* one of your language's fixed-width encodings, or
* a raw byte sequence (when the source code has an integral number of bytes).

If there are other sensible conversions, please leave a comment.

For output, you can choose to

* output truthy/falsy using your language's convention (swapping is allowed), or
* use two distinct, fixed values to represent true (affirmative) or false (negative) respectively.

Standard rules apply. The shortest code in bytes wins.

## Test cases

### Truthy

```
[0, 0]
[999, 999, 999, 1234, 1234]
[1, 2, 2, 2, 3]
[1, 4, 7, 2, 5, 5, 5, 8, 3, 6, 9]
[1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 7]
[1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3]
[0, 0, 0, 0, 0, 0, 0, 0]

```

### Falsy

```
[]
[1]
[1, 3, 5, 7, 9]
[1, 1, 2, 2, 4, 4, 8, 8, 16, 16, 32, 32, 64, 64]

```

# Answer
> 8 votes
# 05AB1E, ~~47~~ ~~47~~ ~~44~~ ~~41~~ 38 bytes

```
œʒ3ôʒ¥J>}gy3ôʒ¥T>SQ}g+3*Ig>Q}ćQ,¥›HUyy

```

Try it online!, or try all test cases (this code can handle in under a minute).

See the codepoints

Returns `0` for true and `[]` for false.

## Explanation

The general approach is this: Test for the existence of a permutation such that if we split it to parts of length 3, and then keep all the valid ones and count them, and multiply by 3, we should get 1 plus the length of the original input.

```
œ       # all permutations
ʒ       # keep those such that:
 3ô      # split to parts of length 3
 ʒ       # keep parts where:
  ¥       # their differences
  J       # joined to a string
  >       # plus one
 }       # (is equal to 1)
 g       # find the length
 y       # push the input again
 3ô      # and split to parts of length 3
 ʒ       # keep parts such that:
  ¥      # their differences
  T>     # 11
  S      # [1, 1]
  Q      # [1, 1] is equal to the differences
 }
 g       # take their lengths
 +       # sum the lengths of the two types of parts
 3*      # times 3
 I       # input
 g       # length
 >       # plus one
 Q       # is equal to the number of valid parts times 3
}
ćQ      # test whether the array is empty, by comparing arr[0] == arr[1:]
,        # output - this suppresses implicit output, so the rest of the code doesn't matter
¥›HUyy  # filler to satisfy the self validation requirement

```

# Answer
> 6 votes
# JavaScript (ES6),  ~~143 122~~  119 bytes

*-24 bytes thanks to @tsh!*

Expects an `Uint32Array`. Returns a Boolean value.

```
n=>(q=([v,...f],e)=>6/v?[e,4,4.5].some(t=>q(f.filter(i=>p>t|v+t%1*p-i||0%[p*=2],p=2),t<p?4>t?4:e:1%0)):e>3)(n.sort(),3)

```

Try it online!

The above function is too slow to validate itself on TIO, so this is using my original answer with an additional optimization:

Try it online!

# Answer
> 4 votes
# Charcoal, ~~128~~ ~~125~~ ~~122~~ 95 bytes

```
≔∧θＥ⌈⁺³θ№θιθＦＥθ⮌Ｅθ⁻λ∧⁼κμ²«Ｗ∧›Ｌι²¬‹⌊ι⁰«≔﹪⊟ι³θＦ²§≔ι±⊕λ⁻§ι±⊕λθ»Ｐ↔¬⌈↔ι»Ｗ⁰«⊟⊟⌊≡↔⊕¬§﹪﹪⁺⁺⁻⁰³ＦＬＬＰＰＷιλθ»

```

Try it online! Uses the Charcoal code page. Add the `-x` argument to show the hex dump which you can compare against the input. Outputs a Charcoal boolean, i.e. `-` for a winning hand, nothing if not. Explanation: Now a port of @Bubbler's algorithm.

```
≔Ｅ⁺³⌈θ№θιθ

```

Count the number of times each integer appears in the array, plus some extra dummy values.

```
ＦＥθ⮌Ｅθ⁻λ∧⁼κμ²«

```

Try each integer in case it's the pair.

```
Ｗ∧›Ｌι²¬‹⌊ι⁰«

```

Repeat until a count becomes negative or the length is reduced to `2`.

```
≔﹪⊟ι³θ

```

Get the number of runs needed to satisfy the next integer.

```
Ｆ²§≔ι±⊕λ⁻§ι±⊕λθ

```

Subtract them from the next two integers.

```
»Ｐ↔¬⌊↔ι

```

Output a `-` if this reduced all the integers to zero (but not negative).

```
»Ｗ⁰«⊟⊟⌊≡↔⊕¬§﹪﹪⁺⁺⁻⁰³ＦＬＬＰＰＷιλθ»

```

Filler bytes to satisfy the source layout, wrapped in a `while` loop whose condition is false.

Original verbose code (without padding): Try it online!

# Answer
> 4 votes
# K (ngn/k), 71 bytes

```
oo::{*0-0!=|/{:[&/0=x;1;|/^%x;0;o@@[1_x;!2;-;3!*x]]}'+@[-2*=3+/x;x;1+]}

```

Try it online!

Based on a polynomial-time algorithm with respect to the maximal element, so it can test all test cases and itself in a second.

Let's call `(x,x,x)` an *x-triplet* and `(x,x+1,x+2)` an *x-sequence*.

* Count the occurrence of each number in `[0, 1, 2, ...]` up to the maximal element that appears in the input. Let's call it C.
* For `i` from 0 to the maximum index of C,
    + Construct a copy of C where `i`-th element is subtracted by 2. (i.e., Assume a pair is `(i,i)`.)
    + Repeat until one of the halting condition is met:
        - If the remaining array is all zeros, return true.
        - If the remaining array contains a negative value, return false.
        - Otherwise, pop `x` from the front, and subtract `x%3` from the first two elements. (i.e., Maximally create `j`-triplets and try creating `j`-sequences for the remaining `j`s.)
* If any choice of `i` gives true, return true. Otherwise return false.

If a partition exists and it contains three or more `j`-sequences for some `j`, three copies of `j`-sequences can be replaced with `j`-, `j+1`-, and `j+2`-triplets to get another valid partition. Also, when considering all possible partitions where the minimum value is `j`, choosing to have three `j`-sequences (compared to one `j`-triplet) has the effect of fixing a `j+1`\- and `j+2`-triplet from the remaining numbers, leaving a strict subset of choices afterwards. Therefore, it suffices to check if a greedy partitioning (favoring triplets) leads to a valid one.

```
{|/{:[&/0=x;1;|/^%x;0;o@@[1_x;!2;-;3!*x]]}'+@[-2*=3+/x;x;1+]}

+@[-2*=3+/x;x;1+]  construct number-count arrays with all choices of pairs
      =3+/x        identity matrix of size `sum of x + 3`
   -2*             change 1s on the diagonal to -2
 @[        ;x;1+]  for each number i in x, add 1 to i-th row of the above
+                  transpose

{:[...]}'  test if each number-count array is partitionable
&/0=x;1;   if all elements are 0, return 1
|/^%x;0;   if any element is negative, return 0
           (monadic % is square root, which gives 0n for negatives;
            monadic ^ is null-check, which gives 1 for 0n)
o@@[1_x;!2;-;3!*x]  otherwise, update the array and do recursive call
    1_x             remove first element k
        !2          and update 0th and 1st elements by
           - 3!*x   subtracting k%3
o@                  recursive call

|/  return 1 if any is true

*0-0!=  filler that preserves truthiness
oo::    globally assign function to the name oo

```

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

```
f=(A,e,k,n)=>1/n&&!{'1,1':1,'0,0':'B\():'|1}[[e-k,k-n]]?!!0:A+A?A.some((C,j)=>f(A.filter(B=>j--),C,...1/n?[]:[e,k])):e==+k

```

Try it online!

Besides tuplets: `&& ++,,-- --..// AABBCC [\] ijjkkl mno rst {|}`

# Answer
> 3 votes
# Raku, ~~121~~ 116 bytes

```
{sub k(\u){u{*}~~[.2/.1]||?(u{*}:k).grep:{?grep {u (>)$_&&k u (-)$_},^3+$_,[$_,$_,$_]}}(bag |$_)}#%&//:>>?\`aabeqqss

```

Try it online!

The inner subroutine name `k` and its argument `u` were somewhat haphazardly chosen to try to produce more triples and runs.

* `bag |$_` converts the argument list into a `Bag` (a set with multiplicity) which is then given to the inner recursive subroutine `k`.
* The subroutine returns true if `u{*} ~~ [.2/.1]`, that is, if the bag contains a single element with multiplicity 2. This is the pair that a winning mah jong hand must contain.
* Otherwise, for the keys in the bag (`u{*}:k`), return true if the bag is a superset (`u (>) $_`) of either the run , + 1, + 2 (`^3 + $_`) or the triple , , (`[$_, $_, $_]`), and the bag minus those elements (`u (-) $_`) produces a true result when passed to the inner recursive function `k`. (Normally I prefer using the Unicode characters for superset () and set minus (), which are the same number of bytes as the equivalent plain ASCII operators (`(>)` and `(-)` respectively), but then I'd have to repeat both of them twice in the trailing comment for a substantial byte penalty.)

Of course, the trailing comment `#%&//:>>?\`aabeqqss` makes the overall code snippet into a winning numerical mah jong hand. The function takes an infeasibly long time to validate itself; I constructed the comment by visual inspection of the function's character distribution.

The pair is: `~~`

The runs are: `#$%`, `()*`, `()*`, `+,-`, `123`, `[\]`, `[\]`, `^_` plus a backtick I can't figure out how to escape, `pqr`, `pqr`

The triples are: , , `$$$`, `$$$`, `&&&`, `(((`, `)))`, `,,,`, `...`, `///`, `:::`, `>>>`, `???`, `___`, `___`, `aaa`, `bbb`, `eee`, `ggg`, `kkk`, `sss`, `uuu`, `uuu`, `{{{`, `{{{`, `|||`, `}}}`, `}}}`

# Answer
> 3 votes
# Jelly, 50 bytes

```
°þþ&&,@ƑƒWß»Ȥ
WÞW+þ@3’œ&ƑƇœ-@€Ʋ€Ẏ$ƬẎŒɠ%¹Ƈɗ€3‘œ&ƑƇ3

```

Try it online!

The main part is a monadic link that takes a list of integers and returns an empty list for false and a list containing one or more items for truthy. To meet the challenge rules, the program includes another link above the main one which is just filler.

Completes all test cases including itself in about 17 seconds on TIO. Full explanation to follow. Note the footer turns the falsy and truthy outcomes to 0 and 1 for more compact printing.

General explanation:

* Remove every possible combination of runs of three (including removing none)
* Check the remaining integers are in groups of length 0 mod 3, except for one that is of length 2 mod 3

## Explanation

```
°þþ&&,@ƑƒWß»Ȥ | Filler to meet challenge requirements

WÞ                                   | Sort (technically with order based on that after wrapping each item in a list, but this doesn't affect sort order)
  W                                  | Wrap in a list
                   $Ƭ                | Repeat the following until no changes are made, gathering up intermediate results
                Ʋ€                   | - For each list in the lists of lists (example for e.g. [1, 2, 3, 4, 4])
   +þ@3                              |   - Outer addition using 1, 2, 3 e.g. [[[2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [5, 6, 7]]
       ’                             |   - Decrease by 1 e.g. [[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [4, 5, 6]]
        œ&ƑƇ                         |   - Filter, keeping only those lists that were seen in the original list e.g. [[1, 2, 3], [2, 3, 4]]
            œ-@€                     |   - Filter the original list removing each of these in turn [[4, 4], [1, 4]]
                  Ẏ                  | - Join inner lists together, leaving one list of lists
                     Ẏ               | Join all gathered intermediate results into one list of lists
                           ɗ€        | For each list within this list:
                      Œɠ             | - Run lengths
                        %    3       | - Mod 3
                         ¹Ƈ          | - Only keep those non-zero (i.e. those lists that were not a multiple of 3 in length)
                              ‘      | Increase by 1
                               œ&ƑƇ3 | Only keep those that consist of a single 3

```

Some of the code above (e.g. using  rather than ) would be suboptimal in normal code-golf challenges, but here improve length by reducing the amount of filler required.

The runtime is sufficient to complete all the test cases, but as written becomes very inefficient as the number of runs of three consecutive numbers increases. This can be greatly improved by adding a uniquify step (TIO), reducing the run time for all test cases and my original code down to ~0.3 seconds total).

# Answer
> 0 votes
# Ruby, ~~116~~ 92 bytes

Brute force solution checking all permutations until it finds one that matches. Times out on medium inputs, so verification was done using the program below since it doesn't time out as easily.

Recursive approach saving 24 bytes by G B.

```
e=->a{a[2]?a.permutation.any?{_,o,z,*i=_1;_-o==(o-=z)&&o**2<2&&e[i]}:a!=a|a}#"')).11@@A[]ass

```

Attempt This Online!

## Ruby, 137 bytes

Count the number of occurrences of each element. Then, for each element, removes a pair from the count (if possible), then checks if everything else is sequences or triplets.

```
->a{a.any?{t=a.tally;(t[_1]-=2)>=0&&a.sort.all?{|e|t[e]>=0&&((0...t[e]%=3).all?{(e..e+2).all?{|i|t[i]=t[i]&.-1}})}}}#$&*++3;;??\\__lmtty|

```

Attempt This Online!

---
Tags: code-golf, decision-problem, restricted-source, game, self-validating
---


title: Is it a substring of itself?

text:
# Question
Title: Is it a substring of itself?
Given a string, return whether the string is a substring of the program's source code.

Standard quine rules apply, meaning you cannot read your own source code. The length of the input is guaranteed to be less than or equal to the length of the program. You may return any two distinct values, not necessarily truthy and falsey values. You may also submit a function, rather than a full program.

This is a so shortest code wins!

### An example

If your source code is `print(input() = False)`, it should return True for `nt(i` but False for `tupn`.

# Answer
> 10 votes
# Python 2, 41 bytes

```
s="print input()in's=%r;exec s'%s";exec s

```

Try it online!

# Answer
> 6 votes
# JavaScript, 25 bytes

```
f=s=>('f='+f).includes(s)

```

Try it online!

I'm personally not a fan of this, but it's allowed.

## Alternate (invalid?) solution, 19 bytes

This takes input as a regex.

```
f=s=>s.test('f='+f)

```

Try it online!

# Answer
> 5 votes
# Java 8, ~~124~~ 112 bytes (function)

```
p->{String s="p->{String s=%c%s%1$c;return s.format(s,34,s).contains(p);}";return s.format(s,34,s).contains(p);}

```

Try it here.

---

Here is it as full program instead (to see one of the reasons why functions are allowed on PPCG, because some languages -like Java- require very verbose mandatory boilerplate code for full programs).

# Java 8, ~~226~~ 214 bytes (full program)

```
interface M{static void main(String[]a){String s="interface M{static void main(String[]a){String s=%c%s%1$c;System.out.print(s.format(s,34,s).contains(a[0]));}}";System.out.print(s.format(s,34,s).contains(a[0]));}}

```

Try it here.

---

**Explanation:**

* The `String s` contains the unformatted source code.
* `%s` is used to input this String into itself with the `s.format(...)`.
* `%c`, `%1$c` and the `34` are used to format the double-quotes.
* `s.format(s,34,s)` puts it all together.

And then `.contains(...)` is used to check if this source code contains the given input.

# Answer
> 2 votes
# QBIC, 28 bytes

```
?instr(B+B,;)#?instr(B+B,;)#

```

This prints 0 if the input is not a substring of the source, and X otherwise where X is the (first) index of the substring.

## Explanation

```
Latter part:
#?instr(B+B,;)#   Define a string literal B$ with a copy of the source

First part:
?                 PRINT
 instr(   , )     the index of
           ;          the cmd line parameter A$
       B+B            in B$ concatenated with itself

```

`#` defines a string literal in QBIC, and assigns it to the first available string variable. That is `B$` in this program, because `A$` is already taken by `;` (read a string from cmd line). Then, everything up to the delimiter is fed into the literal; the delimiter is a backtick - which also makes it the only ASCII char not includable in string lits. In this case, QBIC doesn't need a backtick, because the literal is terminated at the end of the code by QBIC's auto-close feature. For more information on QBIC's literals, see the Showcase thread.

# Answer
> 2 votes
# Bash, ~~43~~, 28 bytes

```
[[ $BASH_COMMAND = *"$1"* ]]

```

try it online

# Answer
> 2 votes
# Haskell, 92 bytes

```
import Data.List;f s=isInfixOf s$(++)<*>show$"import Data.List;f s=isInfixOf s$(++)<*>show$"

```

Try it online! Obvious extension of the standard quine. Getting rid of the import would be nice, but I doubt `isInfixOf` can be computed in a shorter amount of bytes.

# Answer
> 2 votes
## Wolfram Language (Mathematica), 33 bytes

```
!StringFreeQ[ToString[#0], #1] &

```

Try it online!

# Answer
> 2 votes
# Jelly, 10 bytes

```
“;⁾vṾƓẇ”vṾ

```

Try it online!

### How it works

```
“;⁾vṾƓẇ”vṾ  Main link. No arguments.

“;⁾vṾƓẇ”    Set the left argument and the return value to ';⁾vṾƓẇ'.
         Ṿ  Uneval; yield '“;⁾vṾƓẇ”'.
        v   Dyadic eval; eval ';⁾vṾƓẇ' with argument '“;⁾vṾƓẇ”'.

  ⁾vṾ       Yield 'vṾ'.
 ;          Append it to '“;⁾vṾƓẇ”', yielding the source code.
     Ɠ      Read a string from STDIN.
      ẇ     Check if it's a substring of the source code.

```

# Answer
> 1 votes
# Julia, 72 bytes

I now understand what people mean when they say that quine problems are just variations on the classic quine.

```
x="~y=contains\"x=\$(repr(x));\$x\",y)";~y=contains("x=$(repr(x));$x",y)

```

## Explanation

```
#Defines x to be the next line of the source, with the help of escaping characters
x="~y=contains\"x=\$(repr(x));\$x\",y)";
#Interpolates together a comparison string, including repr(x), the re-escaped from of x, and x itself, for comparison.
~y=contains("x=$(repr(x));$x",y)

```

# Answer
> 1 votes
# Vyxal `D`, 56 bitsv2, 7 bytes

```
`Iǎc`Iǎc

```

Try it Online!

## Explained

```
`Iǎc`Iǎc
      ǎ   # Does all substrings of
`Iǎc`     #   The string "Iǎc"
     I    #   With a version surrounded in backticks prepended to itself
       c  # Contain the input?

```

Created with the help of Luminespire.

# Answer
> 0 votes
# Perl 5, 60 + 2 (-pl) bytes

```
$_=(sprintf$a=q($_=(sprintf$a=q(%s),$a)=~/\Q$_/),$a)=~/\Q$_/

```

try it online

# Answer
> 0 votes
# 05AB1E, 17 bytes

```
0"D34çýIå"D34çýIå

```

Modification of the default `0"D34çý"D34çý` by adding .

Try it online.

**Explanation:**

```
0                    # Push 0 to the stack
                     #  STACK: [0]
 "D34çýIå"           # Push the string 'D34çýIå' to the stack
                     #  STACK: [0, 'D34çýIå']
          D          # Duplicate this string
                     #  STACK: [0, 'D34çýIå', 'D34çýIå']
           34ç       # Push '"' to the stack
                     #  STACK: [0, 'D34çýIå', 'D34çýIå', '"']
              ý      # Join the stack by this '"' delimiter
                     #  STACK: ['0"D34çýIå"D34çýIå']
               I     # Take the input
                     #  STACK: ['0"D34çýIå"D34çýIå', 'Iå"D']
                å    # Check if it's a substring of the source code
                     #  STACK [1]
                     # (Output the top of the stack implicitly)

```

---
Tags: code-golf, decision-problem, quine
---


title: Mixed Number to an Improper Fraction

text:
# Question
Title: Mixed Number to an Improper Fraction
In this challenge you will be converting a mixed number to an improper fraction.

Because improper fractions use fewer numbers, your code will need to be as short as possible.

---

## Examples

```
4 1/2
9/2

12 2/4
50/4

0 0/2
0/2

11 23/44
507/44

```

## Specification

You may assume the denominator of the input will never be 0. The input will always be in the format `x y/z` where x,y,z are arbitrary nonnegative integers. You do not need to simplify the output.

---

This is so shortest code in bytes wins.

# Answer
> 2 votes
# Japt, 10 bytes

Woohoo, currently beating CJam!

```
U*W+V+'/+W

```

Try it online!

### How it works

```
       // Implicit: [U,V,W] = eval(input). This automatically discards the slash.
U*W+V  // Calculate the new numerator: (whole part * denominator) + numerator.
+'/+W  // Add the slash and the denominator.
       // Implicit: output last expression

```

# Answer
> 11 votes
# LabVIEW, 29 LabVIEW Primitives

# Answer
> 7 votes
## CJam, ~~16~~ ~~15~~ 14 bytes

```
l'/']er~:Xb'/X

```

or

```
l'/']er~_@b'/@

```

Test it here.

## Explanation

```
l      e# Read input.
'/']er e# Replace the "/" with a "]".
~      e# Evaluate the string as code. If the input was "i n/d", this pushes [i n] d.
:X     e# Store the denominator in X.
b      e# Treat [i n] as base-d digits. This effectively computes i*d + n.
'/     e# Push a slash.
X      e# Push the denominator.

```

The other version avoids using a variable by using a bit more stack shifting.

# Answer
> 4 votes
## Mathematica, 58 bytes

```
ToExpression@StringReplace[#," "->"+"]~ToString~InputForm&

```

This returns the simplified result. If outputting a rational number instead of a string is fine, we can save 19 bytes:

```
ToExpression@StringReplace[#," "->"+"]&

```

# Answer
> 4 votes
## PowerShell, ~~47~~ ~~44~~ 42 Bytes

Crossed out 44 is still regular 44 ;(

```
$l,$n,$d=$args-split'\D';"$(+$l*$d+$n)/$d"

```

Golfed a couple bytes by using regex `-split`. Golfed a couple more thanks to TessellatingHeckler by swapping the regex.

The `$args-split'\D'` takes our input argument and splits on non-digit characters. Here it performs two splits, one on whitespace, the other on the `/` character. The results are then stored in the three variables using a simultaneous assignment. We then formulate the string output as (the `$l`eft number times the `$d`enominator plus the `$n`umerator) executed as a code block, a `/` slash, and then the `$d`enominator again.

# Answer
> 3 votes
# Java with Ten Foot Laser Pole 1.03, 79+25 (import) = 104 bytes

Requires `import sj224.tflp.math.*;`

```
String m(String[]a){return ""+new BigRational(a[0]).add(new BigRational(a[1]));}

```

This will almost certainly work with 1.04 as well, but so far I've only tested it with 1.03 because I already happened to have a java project set up with 1.03 in the build path.

# Answer
> 3 votes
# JavaScript (ES6), ~~44~~ 41 bytes

```
m=>([x,y,z]=m.match(/\d+/g),+y+x*z+"/"+z)

```

*Saved 3 bytes thanks to @ETHproductions!*

## Explanation

Very simple.

```
m=>
  ([x,y,z]=m.match(/\d+/g), // x, y and z = numbers from input
    +y+x*z                  // numerator
    +"/"+z                  // denominator
  )

```

## Test

Test is without destructuring assignment to work in most browsers.

```
var solution = m=>+(p=m.match(/\d+/g))[1]+p[0]*p[2]+"/"+p[2]
```

```
<input type="text" id="input" value="11 23/44" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```

# Answer
> 2 votes
# Bash + coreutils, 28

```
dc<<<${@/\// }sarla*+n47Plap

```

`$@` expands to all command-line parameters, so `${@/\// }` expands to all command-line parameters with `/` replaced with , which is put on `dc`'s stack. The rest is simple stack manipulation and arithmetic.

# Answer
> 2 votes
# Julia, ~~58~~ 50 bytes

```
s->eval(parse((r=replace)(r(s," ","+"),"/","//")))

```

This is an anonymous function that accepts a string and returns a `Rational` type object. To call it, give it a name, e.g. `f=s->...`.

We can take advantage of the fact that the input can be manipulated slightly to be an expression that evaluates to a rational. In particular, an integer plus a rational is a rational, and rationals are denoted with double slashes. So if we turn `4 1/2` into `4+1//2`, the evaluated result will be `9//2`.

Ungolfed:

```
function f(s::AbstractString)
    # Replace the space in the input with a plus
    r1 = replace(s, " ", "+")

    # Replace the / with //
    r2 = replace(r1, "/", "//")

    # Parse the resulting expression as a rational
    return eval(parse(r2))
end

```

# Answer
> 2 votes
# Smalltalk – 76 characters

The input exactly matches the array delimiter and inherent fraction representation of Smalltalk. If it just weren't so verbose, it could have been a serious contender!

```
Compiler evaluate:'|p|p:=0.#(',FileStream stdin nextLine,')do:[:q|p:=p+q].p'

```

It's too bad simplification wasn't a requirement, Smalltalk does it automatically!

# Answer
> 2 votes
# Haskell, ~~74~~ ~~67~~ 63 bytes

```
r=read
f x|(a,(c,s:d):_)<-lex<$>lex x!!0=show(r a*r d+r c)++s:d

```

Try it online!

## Explanation

As H.PWiz figured out we can use Haskell's lexer here to break up the string into it's parts. (Earlier I was using `span(>'/')`) And Laikoni pointed out that `<$>` works just like `mapSnd` from `Data.Tuple`.

The pattern guard breaks up our code into the three numbers we want using `lex`. `lex` invokes haskell's lexer to break off the first token. It returns a list with each element representing a possible way to parse the string. These elements are tuples with the first element being the first token and the rest of the string being the second element. Now since the input format is very regular we are only ever going to have exactly one parse, so we can always take the first one. The first thing we do is invoke `lex` on the input

```
lex x

```

Then we unwrap it from it's list giving us a 2-tuple

```
lex x!!0

```

The first token will be the whole part of the mixed fraction leaving the fraction prepended by a space to still parse. Then since tuples are `Functors` we can use `(<$>)` an alias for `fmap` to apply `lex` to the second element of the tuple.

```
lex<$>lex x!!0

```

This eats through the space and breaks off the next token, the numerator of our fraction. Now we bind this to a pattern match using `<-`. Our pattern is

```
(a,(c,s:d):_)

```

`a` grabs the whole part of the fraction, our first token. `:_` unwraps the list resulting from our second `lex`. `c` grabs the second token we lexed, that is the numerator of the fraction. Everything that remains is bound to `s:d` which splits it into its first character, guaranteed by the format to be a `/` and the remainder which will be the denominator.

Now that we have parsed the input we do the actual computation:

```
show(r a*r d+r c)++s:d

```

Where `r` is the read function we bound earlier.

It is important to note that `lex` returns a list empty if it fails and non-empty if it succeeds. Why this is not a `Maybe` I do not know.

# Answer
> 2 votes
# 05AB1E, ~~17~~ 15 bytes

```
#`'/¡R`Š©*+®'/ý

```

-2 bytes thanks to *@MagicOctopusUrn*.

Try it online or verify all test cases.

**Explanation:**

```
#`         # Split input by spaces and push all items to the stack
           #  i.e. "4 1/2" → "4" and "1/2"
  '/¡      # Push the second item by "/"
           #  i.e. "1/2" → [1,2]
     R`    # Revert the list, and also push all items to the stack
           #  i.e. [1,2] → [2,1] → 2 and 1
Š          # Triple-swap the stack
           #  [4,2,1] → [1,4,2]
 ©         # Store the 2 in the register
  *        # Multiple the top two items
           #  4 and 2 → 8
   +       # Add the top two items
           #  1 and 8 → 9
®          # Push the 2 from the register to the stack again
 '/ý       # Join the two items by "/"
           #  9 and 2 → "9/2"

```

---

With flexible input- and output-format, taking the integers in the order `x,z,y` and outputting the nominator and denominator on separated lines it would be **4 bytes** (which is why I added the -tag to the challenge..):

```
*+²»

```

Try it online or verify all test cases.

**Explanation:**

```
*        # Multiply the first two inputs (x and z)
         #  i.e. 4 and 2 → 8
 +       # Add the third input (y)
         #  i.e. 8 and 1 → 9
  ²      # Take the second input again (z)
   »     # Join the stack by newlines and implicitly print it

```

# Answer
> 2 votes
# Stax, 1 byte

```
+

```

Run and debug it (although there's not much to debug)

The challenge specification says "You do not need to simplify the output." Assuming it's *allowed* to simplify, then there's a built-in instruction in stax to do this. The input is implicitly interpreted as an integer and a rational number. The `+` instruction widens both to rationals, adds, and simplifies. The result is implicitly printed.

# Answer
> 2 votes
# Forth (gforth), 92 bytes

```
: f 0 -rot 3. do 0 -rot >number 1 m+ loop 2drop + >r swap i * + r> <# 0 #s '/ hold + #s #> ;

```

Try it online!

The pain of parsing and formatting...

Takes a string as `pointer length` (gforth standard), and returns a string in the same format.

### How it works

```
: f ( addr u -- addr u )  \ take a string and return a string
  0 -rot      \ ( 0 addr u )
  3. do       \ repeat 3 times...
    0 -rot      \ ( ... 0 0 addr u )
    >number     \ ( ... num 0 addr u ) parse an integer;
                \ `addr` now points to right after the parsed int
    1 m+        \ increment the addr to point to the next integer
  loop        \ end loop ( x y z 0 addr u )
  2drop +     \ discard input string and zero on the top
  >r          \ ( x y R:z ) so the value of z can be copied by `i`
  swap i * +  \ ( x*z+y R:z )
  r>          \ ( x*z+y z )
  <#          \ start formatting the output from the end
  0 #s        \ push z to the output; formatting built-ins take double cells
  '/ hold     \ push a slash
  + #s        \ #s leaves two zeros at the top, so discard one and push x*z+y
  #>          \ finish formatting and get the string ( pointer length )
;

```

# Answer
> 2 votes
# Vyxal, 3 bytes

```
⌈E∑

```

Try it Online! -4 thanks to lyxal

```
⌈   # Split on spaces
 E  # Evaluate each
  ∑ # Sum

```

# Answer
> 2 votes
# Wolfram|Alpha, 0 or 1 byte

```
=

```

The challenge says it's not necessary to simplify the output, but doesn't disallow it. If it's not disallowed, then:

1)The online Wolfram|Alpha interpreter will automatically convert mixed numbers to improper fractions (0 bytes). E.g.:

2)The Wolfram|Alpha interpreter can be called within Mathematica by entering `=` followed by the input (1 byte):

# Answer
> 2 votes
# Thunno 2, 18 bytes

```
OẸ'//ẸsNṭẊ,p+x,'/j

```

Try it online!

#### Explanation

```
OẸ'//ẸsNṭẊ,p+x,'/j  # Implicit input ("x y/z")
OẸ                  # Split on spaces, then dump onto the stack
  '//Ẹ             '# Split the fraction on "/", then dump again
      sN            # Swap and convert the numerator to integer
        ṭ           # Triple swap to get the order [y, x, z]
         Ẋ          # Copy z to the register without popping
          ,p        # Multiply x and z (implicit conversion to int)
            +       # Add this to y (which we converted earlier)
             x,     # Pair this with z (from the register)
               '/j '# Join this pair on "/"
                    # Implicit output

```

# Answer
> 2 votes
# Factor, 43 bytes

```
[ eval( -- x x ) + >fraction [I ${}/${}I] ]

```

Attempt This Online!

Assumes the input must be a string, otherwise this can be shorter. Simplifies the output.

# Answer
> 1 votes
# Perl, ~~82~~ ~~61~~ 38 bytes

```
#!perl -paF/\D/
$_=$F[0]*$F[2]+$F[1]."/$F[2]"

```

This can probably be golfed more.

**Changes**

* Saved 16 bytes by using a regex in `split`, and 5 by using `<>` instead of `<STDIN>`.
* Saved another 16 bytes thanks to Dennis.

# Answer
> 1 votes
# Java, ~~159~~ ~~148~~ ~~142~~ ~~120~~ 110 bytes

```
String m(String[]a){Long b=new Long(a[0]),d=new Long((a=a[1].split("/"))[1]);return b*d+new Long(a[0])+"/"+d;}

```

Saved a bunch of bytes thanks to FlagAsSpam.

# Answer
> 1 votes
# Javascript ES6, 62 bytes

```
p=prompt;b=p(a=+p()).split`/`;alert((+b[1]*a+ +b[0])+"/"+b[1])

```

# Answer
> 1 votes
## Mathematica, 51 bytes

```
Interpreter["ComputedNumber"]@#~ToString~InputForm&

```

Interestingly, Mathematica supports this with a built-in. If outputting a number is allowed, than we only need 28 bytes:

```
Interpreter@"ComputedNumber"

```

# Answer
> 1 votes
# Ruby, 23 bytes

```
->x{eval x.split*?++?r}

```

Try it online!

# Answer
> 1 votes
# ARBLE, 13 bytes

```
a*c+b.."/"..c

```

Try it online!

# Answer
> 1 votes
# Perl 5 with -la -Mfeature=say, 32 bytes 25 bytes

```
m|/|;say$_*$'+$F[1],"/$'"

```

Try it online!

*(-7 bytes thanks to Dom Hastings)*

`$_` is the whole input `x y/z`, which evaluates the value of `x` in numeric contexts (like the `*` here). `$'` is the regex post-match string, which here contains whatever comes after `/` \- so, `z`. To get the `y` value, we use the `-a` flag which splits the input on spaces and places them in the `@F` array. So here, `@F = ("x", "y/z")`, which means `$F[1]="y/z"` which evaluates in `y` in numeric contexts (since `y` is the initial contiguous sequence of digits with `$F[1]`).

# Answer
> 1 votes
# Python 3, ~~78~~ 76 bytes

```
def f(s):a,b=s.split();b,c=b.split('/');return'%s/'%(int(a)*int(c)+int(b))+c

```

Try it online!

# Answer
> 1 votes
# Ouroboros, ~~16~~ 15 bytes

```
rrry@*+n47oMn1(

```

Try it here!

### Explanation

The reason why Ouroboros is great for this challenge: its integer-reading primitive, `r`, skips over any non-digit characters until it comes to a number. So no parsing is required; we just read three numbers and process them. The example below uses the input `23 11/44`.

```
rrr              Read all three numbers to the local stack
                  Local: 23 11 44
   y             Push a copy of the top of the local stack to the shared stack
                  Local: 23 11 44   Shared: 44
    @            Rotate (moving third item to top of stack)
                  Local: 11 44 23   Shared: 44
     *           Multiply
                  Local: 11 1012    Shared: 44
      +          Add
                  Local: 1023       Shared: 44
       n         Output as number
                                    Shared: 44   Output: 1023
        47       Push 47
                  Local: 47         Shared: 44   Output: 1023
          o      Output as character
                                    Shared: 44   Output: 1023/
           M     Move the top value from the shared stack to the local stack
                  Local: 44                      Output: 1023/
            n    Output as number
                                                 Output: 1023/44
             1(  Terminate

```

# Answer
> 1 votes
# Husk, 4 bytes

```
Σmrw

```

Try it online!

`ṁrw` is supposed to work, but there's some bug that returns an empty list. Anyway, hooray for native rational number support.

# Answer
> 1 votes
# GNU AWK, 5+16 = 21 bytes

Command-line argument: `-F |/`

Source code:

```
$0=$1*$3+$2"/"$3

```

Try it online!

The command-line argument sets the field separator to the regex `/ |\//`. Thus, it is easy to map the input as three fields.

# Answer
> 1 votes
# Itr, 1 byte

`+`

Itr has built-in support for rational numbers, including for parsing input numbers.

online interpreter

## Explanation

```
   ; implicit input, by default numbers are separated by spaces
   ; two integers with a '/' between them are interpreted as a fraction
 + ; add the integer part to the fractional part
   ; implicitly output the fraction

```

# Answer
> 1 votes
# Headass, 80 bytes

```
-(----[]]]][]]][{{U]>)D^^D^^^^^R]^}:DON-)}:NE.U[UOUO{^)N+E:]OD-}.U^U[{U^)DPD]P:}

```

Try It Online! Takes character codes as input and outputs as two numbers Numerator, Denominator.

### Explanation:

Fairly straightforward, parses by looping through digits, subtracting 48, and then multiplying by 10 before adding each new number. when it hits a charcode less than 48, it knows to move on to the next number. There's not an easy way to multiply within a single code block to my knowledge, so the next two code blocks respectively copy a bunch of x onto the queue and then add them all up. Probably still golfable within the same approach, I found a few golfs while writing up the explanation, even.

```
-(----[]]]][]]][{{U]>)D^^D^^^^^R]^}:DON-)}:NE. block 0: parses input
-(                                             r3 = -1
  ----[]]]][]]][                               r2 = -48
                {                     N-)}:    while input remains
                 {U]>)            }:             while input + r2 > r3
                      D^^D^^^^^                    r1 *= 10
                               R]^                 r1 += input + r2
                                    DO           enqueue and reset r1
                                           NE  go to block 1
                                             . end block

U[UOUO{^)N+E:]OD-}. block 1: copies x z times onto queue
U[                  r2 = x
  UO                enqueue y
    UO              enqueue z
    U  ^            r1 = z
      {^)   :  D-}  while(r1--){
             ]O       enqueue x
                    }
         N+E        go to block 2
                  . end code block

U^U[{U^)DPD]P:} block 2: sums copies of x and adds y, prints x*z+y and z
U^              r1 = y
  U[            r2 = z
    {U )     :} while items remain unvisited on the queue (all of which are x)
     U^           r1 += x
        DP      print r1
          D]P   print r2

```

# Answer
> 1 votes
# Raku, 25 bytes

```
{m:g/\d+/;$0*$2+$1~"/$2"}

```

Try it online!

`m:g/\d+/` matches all sequences of digits in the input string, setting the variable `$/` to a list of the matches as a side effect. `$0` is equivalent to `$/[0]` and so on, so the rest of the function constructs a the output string with the appropriate arithmetic.

# Answer
> 0 votes
# C, 64

```
main(i,d,n){scanf("%d %d/%d",&i,&n,&d);printf("%d/%d",i*d+n,d);}

```

Reads input from STDIN. Fairly self-explanatory, I think.

# Answer
> 0 votes
# Lua, 123 Bytes

```
m=io.read()z=string x=z.find c=z.sub b=tonumber s=x(m," ")f=x(m,"/")d=c(m,f+1)print(b(c(m,1,s))*b(d)+b(c(m,s,f-1)).."/"..d)

```

# Answer
> 0 votes
# Milky Way 1.6.0, 31 bytes

```
'" "\="/"\=>;<A;A;:>*;A+"/"+<+!

```

Ended up being much longer than I thought it would be.

---

### Explanation

```
'" "\="/"\=>;<A;A;:>*;A+"/"+<+!

'                                # read input from the command line
 " "  "/"               "/"      # push a string to the stack
    \    \                       # split the STOS at the TOS
     =    =                      # dump the TOS to the stack
           >       >             # rotate the stack rightward
            ;  ; ;   ;           # swap the TOS and STOS
             <              <    # rotate the stack leftward
              A A     A          # push the integer representation of the TOS
                  :              # duplicate the TOS
                    *            # multiply the STOS by the TOS
                       +   + +   # add the TOS and STOS
                              !  # output the TOS

```

---

### Usage

```
./mw <path-to-code> -i <input>

```

# Answer
> 0 votes
## Python 2.7, 88 Bytes

```
a=input().split('/');print int(a[-1])*int(a[0].split()[0])+int(a[0].split()[1]),'/',a[1]

```

Try it online!

You have to type the input in quotes.

Probably not the best ...

# Answer
> 0 votes
## Check, 120 bytes

```
>]+>:>32r#v
#d@0+\)  ##:>4;:>5'=:>48-\R-?
dd)R>32-#v
#>15-#v  #?
47r@>@   #v
#dd#v #?
r@>@     #v
    #\d@\: @*@+pd"/"op

```

Try it online!

I might be able to save some bytes by not trying to reuse the parsing loop (the second line). That way I could make the loop more specific, avoid the huge mess of conditionals, and I could use the register for other things.

# Answer
> 0 votes
# C#, 112 bytes

```
s=>{string[]a=s.Split(),b=a[1].Split('/');int o=int.Parse(b[1]);return int.Parse(a[0])*o+int.Parse(b[0])+"/"+o;}

```

Full/Formatted Version:

```
namespace System.Linq
{
    class P
    {
        static void Main()
        {
            Func<string, string> f = s =>
            {
                string[] a = s.Split(), b = a[1].Split('/');
                int o = int.Parse(b[1]);
                return int.Parse(a[0]) * o + int.Parse(b[0]) + "/" + o;
            };

            Console.WriteLine(f("4 1/2"));
            Console.WriteLine(f("12 2/4"));
            Console.WriteLine(f("0 0/2"));
            Console.WriteLine(f("11 23/44"));

            Console.ReadLine();
        }
    }
}

```

# Answer
> 0 votes
# APL (Dyalog Unicode), 31 bytes

```
∊∘(⍕¨⊃,⍨'/',⍨⊃⊥1∘↓)¯1⌽#⍎¨∊∘⎕D⊆⊢

```

Try it online!

Thanks to ngn for the `⊃⊥1∘↓` trick

# Answer
> 0 votes
## PHP, 65 Bytes

Try it online

**Code**

```
<?=(($a=preg_split("/[\s,\/]/",$argv))[0]*$a[2]+$a[1])."/".$a[2];

```

**Explanation**

```
$a=preg_split("/[\s,\/]/",$argv); # Split the string on "/" and " "
(($a)[0]*$a[2]+$a[1]) # as always denominator*whole number + numerator
."/"                  # echo an slash
.$a[2];               # echo de denominator

```

# Answer
> 0 votes
# Java 10, 87 bytes

A lambda from `String` to `String`.

```
s->{var p=s.split(" |/");return new Long(p[0])*new Long(p[2])+new Long(p[1])+"/"+p[2];}

```

Try It Online

---
Tags: code-golf, number, parsing, rational-numbers
---


title: Finite Cantor's Diagonal

text:
# Question
Title: Finite Cantor's Diagonal
Given a list of `N` integers, each with `N` digits, output a number which differs from the first number because of the first digit, the second number because of the second digit, etc.

### Example

Given this list:

```
1234
4815
1623
4211

```

The number `2932`'s first digit is different from the first number's first digit, its second digit is different from the second number's second digit, etc. Therefore it would be a valid output.

### Inputs

* You may take both the list and `N` as input, or only the list if you wish.
* Each integer in the list will necessarily have as many digits as the length of the list (`N`)
* Numbers will not have any leading zeroes
* The input list must contain numbers and not strings.
* You may take inputs as function arguments, through `STDIN`, or anything similar.
* You may assume that the list will not be longer than 10 elements (and no number in the list will be bigger than `2147483647`)

### Outputs

* It is not sufficient that the output is not in the list. The digits must differ as explained above.
* You can use any digit selection strategy that respects the constraint of different digits.
* The number cannot have leading zeroes
* You may output the number through `STDOUT`, return it from a function, etc.

### Test cases

```
Input:
12345678
23456789
34567890
45678901
56789012
67890123
78901234
89012345

Possible output: 24680246

Input:
1

Possible output: 2

```

### Scoring

This is , so the shortest answer in bytes wins.

# Answer
# Jelly, ~~8~~ 7 bytes

1 byte saved thanks to Dennis.

```
DŒDḢỊ‘Ḍ

```

Try it online!

### Explanation

```
DŒDḢỊ‘Ḍ    Main link. Takes list as argument.
D          Convert each integer to decimal.
 ŒD        Get the diagonals.
   Ḣ       Get the first diagonal.
    Ị      Check if every digit <= 1.
     ‘     Increment every digit.
      Ḍ    Convert back to integer from decimal.

```

Converts each digit to `1`, except `0` and `1` becomes `2`.
> 5 votes

# Answer
## CJam (15 14 bytes)

```
qN/ee{:=i2%)}%

```

Online demo

Thanks to Adnan for a one-byte saving.

### Dissection

```
qN/    e# Split input on newlines
ee{    e# Label each line with its index and map:
  :=i  e#   Get the character at the same index (i.e. diagonalise)
  2%)  e#   Compute (ASCII value mod 2) + 1
       e#   Maps 0 1 2 3 4 5 6 7 8 9
       e#     to 1 2 1 2 1 2 1 2 1 2
}%

```
> 8 votes

# Answer
# Python 2, ~~47~~ 45 bytes

```
lambda x,n:int(`x`[1::n+3])%(10**n/2)+10**n/9

```

*Thanks to @xnor for golfing off 2 bytes!*

Test it on Ideone.

### How it works

``x`` yields a string representation of the list **x**.

For the first test case, this gives the *string*

```
[92345678, 23456789, 34567890, 45678901, 56789012, 67890123, 78901234, 89012345]

```

`[1::n+3]` retrieves every **(n + 3)**th character – where **n** is the length of **x** starting with the second one. Accounting **2** characters for `,`, we retrieve the first digit of the first number, the second digit of the second number, etc.

```
[92345678, 23456789, 34567890, 45678901, 56789012, 67890123, 78901234, 89012345]
 ^          ^          ^          ^          ^          ^          ^          ^

```

We now take the number modulo **10n ÷ 2** to map the first digit in the range **\[0, 4\]**.

For **93579135**, we get **93579135 % 50000000 = 43579135**.

Finally, we add **10n ÷ 9** to the last result, which increments – wrapping around from **9** to **0** – all digits by **1** (no carry) or **2** (with carry).

For **43579135**, we get **43579135 + 11111111 = 54690246**.
> 7 votes

# Answer
# MATL, ~~11~~ ~~10~~ 9 bytes

```
VXd9\QV!U

```

Takes only a column vector of integers as input. `N` is not provided.

**Try it Online**

**Explanation**

```
    % Implicity grab input as column vector of numbers
V   % Convert the input column vector into a 2D character array
Xd  % Grab the diagonal elements of the character array
9\  % Take the modulus of each ASCII code and 9
Q   % Add 1 to remove all zeros
V   % Convert the result to a string
!   % Transpose to yield a row vector of characters
U   % Convert back to an integer (as per the rules)
    % Implicitly display result

```
> 4 votes

# Answer
# Pyth, 11 bytes

```
jk.eh!ts@`b

```

Simple loop, change every digit to 1, except 1 becomes 2.
> 3 votes

# Answer
# Retina, ~~39~~ ~~38~~ 37

```
(?<=(.*¶)*)(?<-1>.)*(.).*¶
$2
T`d`121

```

Saved 1 byte thanks Martin!

Requires a trailing linefeed in the input.

Gets diagonals and translates 0 and 2-9 to 1 and 1 to 2.

The basic idea for getting the diagonals is to push a capture for each row above the current row and then consume a capture to match a character, then keep the next character.

Try it online
> 3 votes

# Answer
# Java, 93 bytes

```
String k(int n,int[]a){String s="";for(int i=0;i<n;)s+=(a[i]+s).charAt(i++)<57?9:1;return s;}

```

### Ungolfed

```
String k(int n, int[] a) {
    String s = "";
    for (int i = 0; i < n; )
        s += (a[i] + s).charAt(i++) < 57 ? 9 : 1;
    return s;
}

```

### Output

```
Input:
12345678
23456789
34567890
45678901
56789012
67890123
78901234
89012345

Output:
99991999

Input:
1234
4815
1623
4211

Output:
9999

```
> 3 votes

# Answer
# J, ~~26~~ 22 bytes

```
1+1>:i.@#{"_1"."0@":"0

```

Similar approach to the others using the `<= 1` and `increment` method of the diagonal.

## Usage

Only requires the list of integers as an argument.

```
   f =: 1+1>:i.@#{"_1"."0@":"0
   f 1234 4815 1623 4211
2 1 1 2
   f 92345678 23456789 34567890 45678901 56789012 67890123 78901234 89012345
1 1 1 1 1 2 1 1

```
> 3 votes

# Answer
# Python 2, 54 bytes

```
d,r=1,""
for n in input():r+=`1+-~n/d%9`;d*=10
print r

```
> 2 votes

# Answer
# Java, 94 bytes

```
int c(int[]d){int p=1,r=0,l=d.length,i=0;for(;i<l;p*=10)r+=(d[l-++i]/p%10==1?2:1)*p;return r;}

```

Pure numeric operations for the win! :)

### Sample input/output:

```
8            <-- size
12345678     <-- start of list
23456789
34567890
45678901
56789012
67890123
78901234
89012345     <-- end of list
21111211     <-- result from ungolfed code
21111211     <-- result from golfed code

```

### Full program (with ungolfed code):

```
import java.util.Scanner;

public class Q79444 {
    int cantor_ungolfed(int[] data){
        int power = 1;
        int result = 0;
        for(int i=0;i<data.length;i++){
            result += (((data[data.length-i-1]/power))%10==1? 2 : 1)*power;
            power *= 10;
        }
        return result;
    }
    int c(int[]d){int p=1,r=0,l=d.length,i=0;for(;i<l;p*=10)r+=(d[l-++i]/p%10==1?2:1)*p;return r;}
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] input = new int[n];
        for(int i=0;i<n;i++){
            input[i] = sc.nextInt();
        }
        System.out.println(new Q79444().cantor_ungolfed(input));
        System.out.println(new Q79444().c(input));
        sc.close();
    }
}

```
> 2 votes

# Answer
# Reng v.3.3, 60 bytes

```
k1-#kaiír1ø          ~; !nb$<
1[å{$}k*$k1-#k)9(-#oa$;]o)ks^$

```

For Reng, that was rather simple. Try it here! Input is a space-separated list of numbers.

## 1: init

```
k1-#kaiír1ø

```

`k` is the number of inputs (number of numbers), and we decrement by 1 and restore for the loop stage. `aií` takes all input. `r` reverses the stack for the processing of input.  goes to the next line.

## 2: loop

```
1[å{$}k*$k1-#k)9(-#oa$;]o)ks^$

```

`1[` takes the top item off the stack and into a new stack. `å` splits it into digits. `{$}` pushes a code block containing the operation "drop"; this is repeated `k` times (`k*`) and the code block is dropped (`$`. `k1-#k` decrements `k`. `)9(` puts `9` at the STOS, and `-` subtracts TOS from the STOS. `#o` stores this number in `o`, and `a$;` drops all the members of the stack. `]` closes the parent stack. `o` puts `o` back at the top; this is our digit we're saving. `)` moves it to the bottom so that we can continue our looping. `s` usually checks for non-input (i.e., equality to `-1`), but we can use it to break out of our loop when `k == -1`. So `s^` goes up when `k == -1`. `$` drops `k` from the stack, and our loop begins again.

## 3: final

```
                     ~; !nb$<

```

`<` directs the pointer left, and `$` drops `k` from the stack. `b` is a leftway mirror, so we enter through it, but it bounce back when hitting `;`, a stack-condition mirror. `!n` prints a digit if and only if we're going left. `~` ends the program when we're done printing.
> 2 votes

# Answer
# Ruby, 21 bytes

```
$><<$_[$.-1].hex%2+1

```

A full program. Run with the `-n` flag. Uses the following mapping: `n -> n%2+1`.
> 2 votes

# Answer
# Perl, 18 bytes

Includes +1 for `-p`

Run with the input lines on STDIN. Output is 1 except 2 when the diagonal is 1

`cantor.pl`

```
#!/usr/bin/perl -p
pos=$.;$_=/1\G/+1

```
> 2 votes

# Answer
# Pyth, 14 bytes

```
s.e|-\1@bk\2`M

```

Try it online!
> 1 votes

# Answer
# J, 37 bytes

```
f@(9&-@"."0@((>:@#*i.@#){f=:[:,":"0))

```

Can probably be golfed, but I forgot if there was a command for "diagonals".
> 1 votes

# Answer
# Mathematica 52 bytes

```
FromDigits[Mod[#,2]+1&/@Diagonal[IntegerDigits/@#]]&

```

This follows the approach of Peter Taylor and others (without using Ascii codes).

Example

```
FromDigits[Mod[#,2]+1&/@Diagonal[IntegerDigits/@ #]]&[{1234,4815,1623,4211}]

```

> 2112
> 1 votes

# Answer
# ClojureScript, 58 chars

```
#(int(apply str(map-indexed(fn[i x](- 9(get(str x)i)))%)))

```

Type requirements made this a little longer than necessary, and `map-indexed` being so many chars didn't help.

Often my submissions are valid Clojure as well, but this is using some of ClojureScript's leakiness with JavaScript. Subtraction of a number and string coerces the string to a number--that is, `(- 9 "5")` equals `4`.
> 1 votes

# Answer
**PHP, 46/41/40 bytes**

```
while($a=$argv[++$i])echo($b=9-$a[$i-1])?$b:1;

while($a=$argv[++$i])echo$a[$i-1]==7?6:7;

while($a=$argv[++$i])echo($a[$i-1]%2)+1;

```

Various digit selectors for comparison. I thought "9-digit" would be shortest, but the special case needed to keep a zero out of the first digit overwhelms it.

Fed from CLI arguments:

```
php -r "while($a=$argv[++$i])echo($b=9-$a[$i-1])?$b:1;" 12345678 23456789 34567890 45678901 56789012 67890123 78901234 89012345
86421864

```
> 1 votes

# Answer
# JavaScript (ES6), 41

The %9+1 trick is borrowed from Suever's answer. For once, `.reduce` beats `.map`. Note, the `+=` operator is used to avoid parentheses.

```
a=>+a.reduce((t,n,d)=>t+=(n+t)[d]%9+1,'')

```
> 1 votes

# Answer
# Vyxal, 49 bitsv2, 6.125 bytes

```
vfÞ/ċ›ṅ

```

Try it Online!

Port of Jelly
> 1 votes

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


# Question
Title: Raise integer x to power x, without exponentiation built-ins
**Task -** The title pretty much sums it up: raise an integer *x* to power *x*, where `0<x`.

**Restrictions:**

* Use of exponentiation, `exp()`, `ln()`, and any other powers-related language built-ins, like `pow()`, `x^x`, `x**x` is forbidden.
* You can assume that the given integer fits the limits of the programming language of your choice.

**Test cases:**

```
Input | Output
---------------
2     | 4
3     | 27
5     | 3125
6     | 46656
10    | 10000000000

```

---

This is , so the shortest program in bytes wins.

# Answer
> 18 votes
# Python, 25 bytes

```
lambda n:eval('1'+'*n'*n)

```

Try it online!

# Answer
> 17 votes
# APL (Dyalog), 4 bytes

For *xx*, takes *x* as left argument and *x* as right argument.

```
×/⍴⍨

```

Try all cases online!

`×/` product of

`⍴⍨` arg copies arg

And here here is one that handles negative integers too:

```
×/|⍴|÷1⌊|×⊢

```

Try all cases!

`×/` the product of

`|` absolute value

**r**epetitions of

`|` the absolute value

`÷` divided by

`1⌊` the **L**esser of 1 and

`|` the absolute value

`×` times

the argument

The built-in Power primitive is:

```
x*y

```

# Answer
> 10 votes
## Mathematica, 16 bytes

I've got two solutions at this byte count:

```
1##&@@#~Table~#&

```

Here, `#~Table~#` creates a list of `n` copies of `n`. Then the `List` head is replaced by `1##&` which multiplies all its arguments together.

```
Nest[n#&,1,n=#]&

```

This simply stores the input in `n` and then multiplies `1` by `n`, `n` times.

# Answer
> 6 votes
# JavaScript (ES6), ~~33~~ ~~28~~ ~~25~~ 24 bytes

```
n=>g=(x=n)=>--x?n*g(x):n

```

---

## Try It

```
f=
n=>g=(x=n)=>--x?n*g(x):n
o.innerText=f(i.value=3)()
i.oninput=_=>o.innerText=f(+i.value)()
```

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

---

## History

### 25 bytes

```
f=(n,x=n)=>--x?n*f(n,x):n

```

### 28 bytes

```
n=>eval(1+("*"+n).repeat(n))

```

### 33 bytes

```
n=>eval(Array(n).fill(n).join`*`)

```

# Answer
> 6 votes
# R, 22 bytes

reads `x` from stdin.

```
prod(rep(x<-scan(),x))

```

generates a list of `x` copies of `x`, then computes the product of the elements of that list. When `x=0`, the `rep` returns `numeric(0)`, which is a numeric vector of length `0`, but the `prod` of that is 1, so `0^0=1` by this method, which is consistent with R's builtin exponentiation, so that's pretty neat.

Try it online!

# Answer
> 6 votes
# Regex  (ECMAScript+`(?^*)`RME), 13 bytes

```
^(x(?^*x+))*$

```

Takes its input in unary, as a string of `x` characters whose length represents the number. Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method. It can yield outputs bigger than the input, and is really good at multiplying.)

Try it on replit.com

This version uses molecular lookinto, a new feature in RegexMathEngine. The basic form `(?^*`...`)` matches the expression inside it against the entire input string. (With a parameter, it evaluates it against the contents of a backreference, e.g. `(?^5*`...`)` to look into `\5`.)

On every iteration of the outer loop, there are \\$n\\$ possible matching states of the inner loop, and at the end of \\$n\\$ iterations, the match is complete. In a complete match, each iteration can independently be at any one of \\$n\\$ states, so there are \\$n^n\\$ total possible matches.

Changing the `*` at the end to `+` would make it give a result of \\$0\\$ for \\$n=0\\$.

```
^           # tail = N = input number
(
    x       # tail -= 1
    (?^*    # Non-atomic lookinto - starts with tail = N
        x+  # Create a choice between N possibilities
    )
)*$         # Loop as many times as possible, minimum 0. This will loop N times,
            # because it subtracts 1 from tail on each iteration. The minimum of
            # 0 iterations gives a correct result of 1 for N==0.

```

The constant-power \\$n^k\\$ version of this can be seen in Quartic Summation, for which there is also a method that doesn't require non-atomic lookaround. It might be impossible to implement \\$n^n\\$ without non-atomic lookaround, due to it being impossible to create \\$m\\$ number of choices (with the value \\$m\\$ being accessed via a backreference) without the guarantee of having \\$O(m)\\$ avaiable space.

The constant-base \\$k^n\\$ version of this would be e.g. `^((.+)*)+` or `^(x(||))*$` for \\$3^n\\$.

# Regex  (PCRE2 v10.35+), 26 bytes

```
^(x((?<*(?*^x+|(?2)).)))*$

```

Attempt This Online!

This solution uses non-atomic recursion, lookahead, and lookbehind to emulate non-atomic variable-length lookbehind. The algorithm used is the same as that of the 13 byte version.

```
^                           # tail = N = input number
(
    x                       # tail -= 1
    (                       # Define subroutine (?2)
        (?<*                # Non-atomic lookbehind
            (?*             # Non-atomic lookahead
                ^           # If we've reached tail==0, then:
                x+          # create a choice between N possibilities.
            |
                (?2)        # Otherwise, recursively call (?2).
            )
            .               # tail += 1 (Go back 1 character at a time)
        )
    )
)*$                         # Loop as many times as possible, minimum 0. This
                            # will loop N times, because it subtracts 1 from
                            # tail on each iteration. The minimum of 0 iterations
                            # gives a correct result of 1 for N==0.

```

The equivalent in a hypothetical engine with real (not emulated) non-atomic variable-length lookbehind would be `^(x(?<*^x+.*))*$` (**16 bytes**).

## Regex  (PCRE2 v10.35+ without lookbehind), 59 bytes

```
^(?=(x*)\1(x?))(((?*x+(?!\1)()?|\2+$))x(?(?=\2\1)(?4)))*\1$

```

Attempt This Online!

This demonstrates this to be possible without the use of lookbehind or recursion. It works by emulating operation on \\$n\\$ within the space of \\$n/2\\$, using one of those halves as a counter for the outer loop, and the other half for the inner loop.

(I wrote this version on July 29, and am finally posting it now.)

```
^                         # Anchor to start; tail = N = input number
(?=(x*)\1(x?))            # \1 = floor(N / 2); \2 = N % 2
(
    (                     # Define subroutine (?4):
        (?*
            x+(?!\1)      # Add \1 to possibility count
            ()?           # Double the possibility count of the above
        |
            \2+$          # If \2==1, add 1 to possibility count
        )
    )
    x                     # tail -= 1
    (?(?=\2\1)            # If tail ≥ \2 + \1:
        (?4)              # Call subroutine (?4), to multiply its possibility
                          # count with the above
    )
)*                        # For every possible iteration count, from 0 to the
                          # maximum, add the above to the possibility count
\1$                       # Assert tail == \1

```

## Regex  (ECMAScript+`(?*)`RME / PCRE2 v10.35+), 81 bytes

```
^(?=(x*)\1(x?))((?*x+(?!\1)(|)|\2+$)x((?=\2\1)(?*x+(?!\1)(|)|\2+$)|(?!\2\1)))*\1$

```

Try it on replit.com \- RegexMathEngine
Attempt This Online! \- PCRE2 v10.40+

This is a port of the 59 byte version. Basic ECMAScript lacks not only lookbehind, but subroutine calls and conditionals as well. The only feature added to basic ECMAScript is `(?*`...`)`, molecular lookahead (a.k.a. non-atomic lookahead). Note that `(|)` must be used instead of `()?` due to ECMAScript's no-empty-optional rule.

(I wrote this version on July 29, and am finally posting it now.)

```
^                         # Anchor to start; tail = N = input number
(?=(x*)\1(x?))            # \1 = floor(N / 2); \2 = N % 2
(
    (?*                   # Define "subroutine":
        x+(?!\1)          # Add \1 to possibility count
        (|)               # Double the possibility count of the above
    |
        \2+$              # If \2==1, add 1 to possibility count
    )
    x                     # tail -= 1
    # Multiply the above possibility count with the following:
    (                     # Emulated conditional, upon whether tail ≥ \2 + \1
        (?=\2\1)          # If yes:
        # Call "subroutine" (duplicates it, since this regex flavor lacks
        # subroutine calls) to multiply with the above possibility count
        (?*
            x+(?!\1)
            (|)
        |
            \2+$
        )
    |
        (?!\2\1)          # If no: Use possibility multiplier of 1
    )
)*                        # For every possible iteration count, from 0 to the
                          # maximum, add the above to the possibility count
\1$                       # Assert tail == \1

```

# Answer
> 5 votes
# Pure bash, 43

```
echo $[$1<2?1:$[$1<2?2:$1]#`printf 1%0$1d`]

```

Try it online.

Not sure if this is bending the rules too much - I'm not using any of the listed banned builtins, but I am using base conversion.

* `printf 1%0$1d` outputs a `1` followed by n `0`s
* `$[b#a]` is an arithmetic expansion to treat `a` as a base `b` number, which gives the required result. Unfortunately base \<2 does not work, so the extra `?:` bits handle input n=1.

Maximum input is 15, because bash uses signed 64-bit integers (up to 231-1).

# Answer
> 5 votes
# Standard ML, 42 bytes

```
fn x=>foldl op*1(List.tabulate(x,fn y=>x))

```

Try it online!

Explanation:

```
fn y => x                 (* An anonymous function that always returns the inputted value *)
List.tabulate(x, fn y=>x) (* Create a list of size x where each item is x *)
foldl op* 1               (* Compute the product of the entire list *)

```

# Answer
> 4 votes
## Alice, 13 bytes

```
/o
\i@/.&.t&*

```

Try it online!

### Explanation

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

```

This is a framework for programs that read and write decimal integers and operate entirely in Cardinal mode (so programs for most arithmetic problems).

```
.    Duplicate n.
&.   Make n copies of n.
t    Decrement the top copy to n-1.
&*   Multiply the top two values on the stack n-1 times, computing n^n.

```

# Answer
> 4 votes
# Nibbles, ~~3~~ 2.5 bytes (~~6~~ 5 nibbles)

```
`*^$_

```

Attempt This Online!

Returns the correct answer of \\$1\\$ for an input of \\$0\\$, as it is generally accepted that \\$0^0=1\\$ (even though this challenge doesn't require it, and several of the other answers take advantage of this and return \\$0\\$, or loop infinitely, for an input of \\$0\\$).

The ASCII representation uses `^`, but in this context it's a Replicate operator, not exponentiation.

Explanation, shown with example input of 7:

```
`*^$_
    _     # Input coerced to a list: [7]
   $      # Input: 7
  ^       # Replicate: [7, 7, 7, 7, 7, 7, 7]
`*        # Product (returns 1 for an empty list): 823543

```

The builtin is just **0.5 bytes (1 nibble)**:

```
^

```

Attempt This Online!

# Answer
> 4 votes
# Uiua, 4 bytes

```
/×▽.

```

Try it!

```
  ▽.  # list of N Ns
/×    # product

```

Note: can also do /×↯.

# Answer
> 3 votes
# Jelly, 3 bytes

```
ẋ⁸P

```

**Try it online!**

### How?

```
ẋ⁸P - Main link: x             e.g. 4
 ⁸  - link's left argument, x       4
ẋ   - repeat left right times       [4,4,4,4]
  P - product                       256

```

# Answer
> 3 votes
# Ruby, ~~20~~ 18 bytes

-2 bytes because the spec changed and I no longer need an exponent argument.

```
->x{eval [x]*x*?*}

```

Try it online!

# Answer
> 3 votes
# 05AB1E, 3 bytes

```
.DP

```

Try it online! or Try all examples

```
.D  # pop a,b    push b copies of a
    # 05AB1E implicitly takes from input if there aren't enough values on the stack
    # For input 5, this gives us the array: [5,5,5,5,5]
  P # Take the product of that array
    # Implicit print

```

# Answer
> 3 votes
# Cubix, 19 bytes

```
..@OI:1*s;pu!vqW|($

```

Try it online!

Step by Step

Expands out onto a cube with side length 2

```
    . .
    @ O
I : 1 * s ; p u
! v q W | ( $ .
    . .
    . .

```
* `I:1` Takes the input, duplicates it and pushs 1. This sets up the stack with a counter, multiplier and result.
* `*s;` Multiples the TOS, swaps the result with previous and remove previous.
* `pu` Bring the counter item to the TOS. U-turn. This use to be a lane change, but needed to shave a byte.
* `|($` This was done to save a byte. When hit it skips the decrement. reflects, decrements the counter and skips the no op wrapping around the cube.
* `!vqW` Test the counter. If truthy skip the redirect, put the counter on BOS, change lane back onto the multiplier. Otherwise redirect.
* `|sO@` this is the end sequence redirected to from counter test. Goes past the horizontal reflect, swaps the TOS bringing result to the TOS, ouput and halt.

# Answer
> 3 votes
# x86\_64 machine language for Linux, ~~14 11~~ 10 bytes

```
0:   6a 01                   pushq  $0x1
2:   58                      pop    %rax
3:   89 f9                   mov    %edi,%ecx
5:   f7 ef                   imul   %edi
7:   e2 fc                   loop   5
9:   c3                      retq

```

To Try it online!, compile and run the following C program.

```
const char h[]="\x6a\1\x58\x89\xf9\xf7\xef\xe2\xfc\xc3";

int main(){
  for( int i = 1; i < 4; i++ ) {
    printf( "%d %d\n", i, ((int(*)())h)(i) );
  }
}

```

# Answer
> 3 votes
# Vyxal, 2 bytes

```
ẋΠ

```

Try it Online!

# Answer
> 3 votes
# Desmos, ~~19~~ 17 bytes

```
f(x)=∏_{n=1}^xx

```

Try it on Desmos!

The `^` is not used for exponentation in this case.
-2 bytes thanks to Aiden Chow.

# Answer
> 2 votes
# Haskell, ~~24~~ ~~23~~ 21 bytes

```
f y=product$y<$[1..y]

```

Try it online!

* Saved 1 byte, thanks to Laikoni
* Saved 2 bytes, thanks to nimi

# Answer
> 2 votes
# Stacked, 10 bytes

```
{!1[n*]n*}

```

Try it online!

Two-argument exponentiation for the same size:

```
{%1[x*]y*}

```

Both are functions. Repeats a function that multiplies `1` by `n` `n` times.

# Answer
> 2 votes
# Scala, ~~32~~ 26 bytes

```
n=>List.fill(n)(n).product

```

Try it online! (Added conversion to long in the TIO so it wouldn't overflow on n=10.)

# Answer
> 2 votes
# x86 machine code (Linux), 18 bytes

```
31 c0 ff c0 31 db 39 df 74 07 0f af c7 ff c3 eb f5 c3

```

It expects a C declaration as follows `extern int XpowX(int)`.

### Disassembled

```
XpowX:
  # edi : input register
  # ebx : counter
  # eax : result register
  xor  %eax, %eax    # result  = 0
  inc  %eax          # result += 1
  xor  %ebx, %ebx    # counter = 0
  loop:
    cmp  %ebx, %edi  # if (counter == input)
    je   done        #   return result
    imul %edi, %eax  # result  *= input
    inc        %ebx  # counter += 1
    jmp   loop
  done:
    ret

```

# Answer
> 2 votes
# Japt, 4 bytes

```
ÆUÃ×

```

Try it online!

## Explanation

```
ÆUÃ×       // implicit: U = input integer
Uo{U} r*1  // ungolfed

Uo{ }      // create array [0, U) and map each value to...
   U       //   the input value
      r*1  // reduce with multiplication, starting at 1
           // implicit output of result

```

# Answer
> 2 votes
# Flurry, 16 bytes

```
<>{{}}<<>()>{}{}

```

### Run example

```
$ ./flurry -nin -c "<>{{}}<<>()>{}{}" 4
256
$ ./flurry -nin -c "<>{{}}<<>()>{}{}" 5
3125

```

Multiply `n` `n` times to 1. The lambda expression is `n (\x. \y. n (x y)) I` where `\y. n (x y)` or `n ∘ x` is the product of Church numeral of `n` and `x`, and its SKIB-transformation is as follows:

```
n (\x. \y. n (x y)) I
S I (\n. \x. \y. n (x y)) n I
S I (\n. \x. S (K n) x) n I
S I (\n. S (K n)) n I
S I (S ∘ K) n I

```

So the direct translation of this expression into Flurry gives the code above.

Expanding the `S` in front gives `n ((S ∘ K) n) I`, which does not change bytes:

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

```

If direct exponentiation is allowed, it is **6 bytes**: `({}){}` (pop n, push n, pop n; evaluates to `n n`), because `n m` evaluates to `m^n` when `n` and `m` are Church numerals.

# Answer
> 2 votes
# 1+, ~~29~~ ~~27~~ ~~25~~ 24 bytes

```
1."1##/"\*\1+\"/^"/<1+#:

```

This was already shockingly short, given how messy it is to create a halting loop... I did a poor job on stack manipulation, so it can probably be improved.

## Special notes on 25 -\> 24

> **Remember that you're programming in brainfuck.** It's tempting to avoid confusion and tedium by thinking in terms of higher-level abstractions as much as possible, rather than thinking in brainfuck. This can buy enough control to make a working program, usually at the cost of such inefficiencies as: -excessive pointer movement, sometimes as simple as "\>+\<-\>" and sometimes less apparent; often a result of doing things in an intuitively appealing order. -- Daniel B. Cristofani

This applies to 1+ as well. I designed this program with pseudo-code, which results in two consecutive `/`s - cuz there are only three elements on the stack, replacing it with `\` saves one byte.

# Answer
> 2 votes
# Arn, 8 bytes

```
xõPÑ_=>$

```

# Explained

Unpacked: `*v{_}\1=>`

```
    \        Fold...
*            ...with multiplication after...
v{           ...mapping with key of v...
  _          ...by replacing with input
}            End map
      1      Literal one
        =>   inclusive range to...
          _  ...input, implied

```

# Answer
> 2 votes
# Rust, 37 bytes

```
|x|(|mut y|{for _ in 1..x{y*=x}y})(x)

```

Try it online

This might be able to be shortened once bindings\_after\_at stabilizes by using `|mut y@x|` instead.

# Answer
> 2 votes
# Perl 5 \+ `-p`, 17 bytes

```
$_=eval"$_*"x$_.1

```

Try it online!

# Answer
> 2 votes
**UPDATE 2** ::

and finally, the super overskill version that uses binary squaring algorithm, safely catches division by zero, and properly handles negative integer bases and negative integer exponents — *that's quite a nifty bit of data sanity checking and edge case handling for 3 lines of code that has no hard-coded constants at all, plus avoiding use of the exponentiation operator (`^` or `**`)*

Center column is function output, and right most column is reference output.

It could even handle some extremely large magnitude negative exponents, like `x^x` for :

```
-16777213  ^  ()  -5.53904374025776e-121210664
                  -5.53904374025776e-121210664

```

> `-log(!_)` *exists within the function merely to return* `+inf`

```
for __ in -3 -2 -1 0 '' -0 1 2 3; do

    jot 13 -4 |

    gawk -v PREC=2000 -Mbe '

    func ____(___,__,_){return(__+=(_="")<__?_:___)<++_\
        ?(!__?_:___?_/____(___,-__):-log(!_)):__<++_?___\
        :(__%_?___:!!_)*____(___*___,int(__/_))

    } BEGIN { CONVFMT = "%.15g"
           _ = ""
    } ($++NF = " ^ (" (___) ")")^_ + \
      ($++NF = "|" ____(__=$!_,___))^_ + \
      ($++NF = "|" __^(_<___?___:__))' ___="$__"

done

```

>

```
     1  -4  ^  (-3)  -0.015625            -0.015625
     2  -3  ^  (-3)  -0.037037037037037   -0.037037037037037
     3  -2  ^  (-3)  -0.125               -0.125
     4  -1  ^  (-3)  -1                   -1
     5  0   ^  (-3)  +inf                 +inf
     6  1   ^  (-3)  1                    1
     7  2   ^  (-3)  0.125                0.125
     8  3   ^  (-3)  0.037037037037037    0.037037037037037
     9  4   ^  (-3)  0.015625             0.015625
    10  5   ^  (-3)  0.008                0.008
    11  6   ^  (-3)  0.00462962962962963  0.00462962962962963
    12  7   ^  (-3)  0.00291545189504373  0.00291545189504373
    13  8   ^  (-3)  0.001953125          0.001953125

```

>

```
    14  -4  ^  (-2)  0.0625               0.0625
    15  -3  ^  (-2)  0.111111111111111    0.111111111111111
    16  -2  ^  (-2)  0.25                 0.25
    17  -1  ^  (-2)  1                    1
    18  0   ^  (-2)  +inf                 +inf
    19  1   ^  (-2)  1                    1
    20  2   ^  (-2)  0.25                 0.25
    21  3   ^  (-2)  0.111111111111111    0.111111111111111
    22  4   ^  (-2)  0.0625               0.0625
    23  5   ^  (-2)  0.04                 0.04
    24  6   ^  (-2)  0.0277777777777778   0.0277777777777778
    25  7   ^  (-2)  0.0204081632653061   0.0204081632653061
    26  8   ^  (-2)  0.015625             0.015625

```

>

```
    27  -4  ^  (-1)  -0.25                -0.25
    28  -3  ^  (-1)  -0.333333333333333   -0.333333333333333
    29  -2  ^  (-1)  -0.5                 -0.5
    30  -1  ^  (-1)  -1                   -1
    31  0   ^  (-1)  +inf                 +inf
    32  1   ^  (-1)  1                    1
    33  2   ^  (-1)  0.5                  0.5
    34  3   ^  (-1)  0.333333333333333    0.333333333333333
    35  4   ^  (-1)  0.25                 0.25
    36  5   ^  (-1)  0.2                  0.2
    37  6   ^  (-1)  0.166666666666667    0.166666666666667
    38  7   ^  (-1)  0.142857142857143    0.142857142857143
    39  8   ^  (-1)  0.125                0.125

```

>

```
    40  -4  ^  (0)   1                    1
    41  -3  ^  (0)   1                    1
    42  -2  ^  (0)   1                    1
    43  -1  ^  (0)   1                    1
    44  0   ^  (0)   1                    1
    45  1   ^  (0)   1                    1
    46  2   ^  (0)   1                    1
    47  3   ^  (0)   1                    1
    48  4   ^  (0)   1                    1
    49  5   ^  (0)   1                    1
    50  6   ^  (0)   1                    1
    51  7   ^  (0)   1                    1
    52  8   ^  (0)   1                    1

```

>

```
    53  -4  ^  ()    0.00390625           0.00390625
    54  -3  ^  ()    -0.037037037037037   -0.037037037037037
    55  -2  ^  ()    0.25                 0.25
    56  -1  ^  ()    -1                   -1
    57  0   ^  ()    1                    1
    58  1   ^  ()    1                    1
    59  2   ^  ()    4                    4
    60  3   ^  ()    27                   27
    61  4   ^  ()    256                  256
    62  5   ^  ()    3125                 3125
    63  6   ^  ()    46656                46656
    64  7   ^  ()    823543               823543
    65  8   ^  ()    16777216             16777216

```

>

```
   (trimming out the -0 exponent ones since they're same as +0)

```

>

```
    79  -4  ^  (1)   -4                   -4
    80  -3  ^  (1)   -3                   -3
    81  -2  ^  (1)   -2                   -2
    82  -1  ^  (1)   -1                   -1
    83  0   ^  (1)   0                    0
    84  1   ^  (1)   1                    1
    85  2   ^  (1)   2                    2
    86  3   ^  (1)   3                    3
    87  4   ^  (1)   4                    4
    88  5   ^  (1)   5                    5
    89  6   ^  (1)   6                    6
    90  7   ^  (1)   7                    7
    91  8   ^  (1)   8                    8

```

>

```
    92  -4  ^  (2)   16                   16
    93  -3  ^  (2)   9                    9
    94  -2  ^  (2)   4                    4
    95  -1  ^  (2)   1                    1
    96  0   ^  (2)   0                    0
    97  1   ^  (2)   1                    1
    98  2   ^  (2)   4                    4
    99  3   ^  (2)   9                    9
   100  4   ^  (2)   16                   16
   101  5   ^  (2)   25                   25
   102  6   ^  (2)   36                   36
   103  7   ^  (2)   49                   49
   104  8   ^  (2)   64                   64

```

>

```
   105  -4  ^  (3)   -64                  -64
   106  -3  ^  (3)   -27                  -27
   107  -2  ^  (3)   -8                   -8
   108  -1  ^  (3)   -1                   -1
   109  0   ^  (3)   0                    0
   110  1   ^  (3)   1                    1
   111  2   ^  (3)   8                    8
   112  3   ^  (3)   27                   27
   113  4   ^  (3)   64                   64
   114  5   ^  (3)   125                  125
   115  6   ^  (3)   216                  216
   116  7   ^  (3)   343                  343
   117  8   ^  (3)   512                  512

```

> ## ====================================

**UPDATE 1** ::: The shorter version that only does `x^x`, w/o binary squaring

```
jot 15 0 |

```

---

```
gawk 'func ___(__,_){$NF*=(__+=(""~__)*($++_+=!$_))>_?$_ ___(--__):_}!___()'

```

---

```
1
1
4
27
256
3125
46656
823543
16777216
387420489
10000000000
285311670611
8916100448256
302875106592253
11112006825558016

```

> ## ====================================

`awk` \- a LOT of bytes (***123*** ?, per `Deadcode`), but it includes the ***full*** recursive binary squaring algorithm tailored for `x^x` without using ***any*** alphanumerics (other than unavoidable keywords like `function` and `return`) or the power (`^` | `**`) operator :

```
jot 14 |

mawk 'function ____(__,___,_){return(___+=((_="")==___)*__)<(_+=++_)?\
           __+!+__:(___%_?__:!!_)*____(__*__,int(___/_))}$++NF=____($_)'

```

>

```
0 1
1 1
2 4
3 27
4 256
5 3125
6 46656
7 823543
8 16777216
9 387420489
10 10000000000
11 285311670611
12 8916100448256
13 302875106592253
14 11112006825558016

```

Yes this is code golfing so mine is equivalent to Tiger Woods doing 10 strokes at a par 3 in Augusta, but unlike most other entries, this one scales nicely even for extremely large inputs, ***AND***, also being `POSIX`-compliant (not that it matters for golfing)

# Answer
> 2 votes
# Thunno `D`, \\$5\log\_{256}(96)\approx\\$ 4.12 bytes

```
ZOA*P

```

Attempt This Online!

Note: the built-in solution would have been just one character: `^` or `@` (either would work).

#### Explanation

```
ZOA*P # Implicit input
ZO    # Wrap the input in a list
  A*  # Repeat it input times
    P # Take the product of this list
      # Implicit output

```

# Answer
> 2 votes
# Fortran (GFortran), 73 bytes

```
integer(selected_int_kind(32))::n
read*,n;print*,product([(n,j=1,n)]);end

```

Try it online!.

Uses a larger integer type because the implicit integer type overflows doing `10**10`. This solution can compute results up to `170141183460469231731687303715884105727`.
We make an inline anonymous array of `n`s : `[(n,j=1,n)]`, take the `product()`, and `print` the result.

# Answer
> 2 votes
# Nibbles, 3 bytes (6 nibbles)

```
/,$*_@

```

```
/,$*_@
/           # fold from right over
 ,$         # 1..input
   *        # multiplying
     @      # result-so-far with
    _       # input

```

# Answer
> 2 votes
# Rattle, 8 bytes

```
|$+[*~]~

```

Try it Online!

I posted the 9-byte answer and immediately found a way to improve it. This method uses `$` to swap the top of the stack with the existing value in memory (0) then increments to get 1. It otherwise follows the same logic.

# Rattle, 9 bytes

```
|s=1[*~]~

```

Try it Online!

# Explanation

```
|            parse input
 s           save input to memory
  =1         set top of stack to 1
    [  ]~    loop n times where n is the value in memory
     *~      multiply the top of the stack by the value in memory
             (print implicitly)

```

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

*-3 bytes thanks to language creator*

```
┴‼*

```

try it online (uses 3 as example)

## Explanation:

```
┴‼*
┴   ' do this function with the same value for both arguments
 ‼  '   repeat each element of [left] the-element-at-the-corresponding-index-of-[right] times
  * ' multiply elements of resulting list

```

# Answer
> 2 votes
# PowerShell, 20 bytes

```
@($n)*$n-join"*"|iex

```

Try it online!

**Explanation**

```
@($n)*$n-join"*"|iex    # full command
@($n)                   # array consisting of single element
*$n                     # multiply the array element x times
-join"*"                # joins all elements with * separating (3*3*3)
|iex                    # executes the provided expression

```

# Answer
> 2 votes
# Go, ~~53~~ 51 bytes

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

```

Attempt This Online!

* -2 by @The Thonnu: anonymous function

# Answer
> 2 votes
# BQN, 4 bytes

```
×´⥊˜

```

Try it

```
  ⥊˜ # a list of N Ns
×´   # product

```

# Answer
> 2 votes
# Rust, ~~29~~ 26 bytes

Saved 3c

```
|x|(0..x).fold(1,|a,_|a*x)

```

```
|x|(0..x).map(|_|x).product()

```

# Answer
> 2 votes
# Nekomata, 2 bytes

```
ř∏

```

Attempt This Online!

```
ř   Replicate
 ∏  Product

```

# Answer
> 1 votes
# Brachylog, 6 bytes

```
g;?j₎×

```

Try it online!

### Explanation

```
          Example input: 5
g         Group: [5]
 ;?       Pair with the Input: [[5], 5]
   j₎     Juxtapose [5] 5 times: [5, 5, 5, 5, 5]
     ×    Multiply

```

# Answer
> 1 votes
# CJam, 7 bytes

```
ri_a*:*

```

Try it online!

**Explanation**

```
ri       e# Read an int from input
  _      e# Duplicate it
   a*    e# Put the copy in the array and repeat it that many times
     :*  e# Take the product of the array

```

# Answer
> 1 votes
# dc, 24 23 26 22 bytes

This is my first attempt writing a recursive macro in dc. I am sure it is a sub-optimal solution which can be improved a lot.

```
dsr1+[lrr1-d1<F*]dsFxp

```

Try it online!

**Edit:** Thanks **eush77**! -4 bytes.

# Answer
> 1 votes
# Perl 6, 13 bytes

```
{[*] $_ xx$_}

```

`$_ xx $_` evaluates to a list of `$_` copies of `$_` (`$_` being the argument to the anonymous function), and then `[*]` reduces that list with multiplication.

# Answer
> 1 votes
# CJam, 6 bytes

```
ri_m*,

```

Try it online!

```
ri       e# Read integer
  _      e# Duplicate
   m*    e# Cartesian power. The first argument is interpreted as a range
     ,   e# Number of elements. Implicitly display

```

# Answer
> 1 votes
# Retina, ~~49~~ 46 bytes

*Golfed 3 bytes thanks to @Neil*

```
.+
1;$&$*1;$&$*1
{`1(?=1*;(1+);.)
$1
}`1$

\G1

```

Try it online!

Supports positive integers just as stated in the challenge.

# Answer
> 1 votes
## Clojure, 22

```
#(apply *(repeat % %))

```

:)

# Answer
> 1 votes
# Röda, 17 bytes

```
{product([_]*_1)}

```

Try it online!

It's an anonymous function that takes it's input from the stream.

Explanation:

```
{product([_]*_1)}
{               } /* An anonymous function */
         [_]      /* An array containing the input value */
            *_1   /* repeated times the input value */
 product(      )  /* Product of all values in the array */

```

# Answer
> 1 votes
## Batch, 58 bytes

```
@set n=1
@for /l %%i in (1,1,%1)do @set/an*=%1
@echo %n%

```

Only works for single-digit inputs due to 32-bit arithmetic.

# Answer
> 1 votes
# MacOS Bash, 18

```
jot -s* -b$1 $1|bc

```

Try it online.

Also runs on Linux if you install the `jot` utility:

```
sudo apt install athena-jot

```

# Answer
> 1 votes
# brainf\*ck, 148 bytes

```
,[->+>+<<]>>[-<<+>>]++++++++[<------<------>>-]<[->>+>>+<<<<]>>[-<<+>>]>>-[-<<<<<[>[>+>+<<-]>>[<<+>>-]<<<-]>>[-<<+>>]>>>]<<<++++++++[-<<++++++>>]<<.

```

Try it online!

No built-ins ;)

**How it works**

```
,                                       - get ascii input
[->+>+<<]                               - duplicate input
>>[-<<+>>]                              - shift inputs left to start
++++++++[<------<------>>-]             - convert ascii into input numbers
<[->>+>>+<<<<]                          - get loop intervals (same as input #)
>>[-<<+>>]                              - shift input back again
>>-[-<<<<<[>[>+>+<<-]>>[<<+>>-]<<<-]>>  - iterated addition (multiplication)
[-<<+>>]>>>                             - Shift output back into input
]<<<++++++++[-<<++++++>>]<<.            - convert final output to ascii

```

In a nutshell, this works by multiplying `x` (the input) by itself `x` times. (a.k.a. iterating iterated addition). The net result is x^x.

**I/O**

The program takes a single ASCII input, and processes it as it's *ASCII index minus 48*. The *minus 48* is to normalize inputs of actual numbers (`4` becomes `52` -\> `52-48` -\> `4`). To input a number higher than 9, use the next corrosponging ASCII character (`:` -\> `58-48` -\> `10`). The program ouputs in a similar fashion.

**Test I/O**

```
INPUT > PROCESSED INPUT >> OUTPUT > TRANSLATED OUTPUT
1 > 1 >> 1 > 1
2 > 2 >> 4 > 4
3 > 3 >> K > 27

```

Since there are no printable ASCII characters after an input of 3, it can only print numbers *in theory*. Though, you can check all inputs do in fact work on visualizers such as this.

# Answer
> 1 votes
# TI-Basic (TI-84 Plus CE), 9 bytes

```
prod(seq(Ans,A,1,Ans

```

Input is from `Ans`, output is stored in `Ans`.

Run with `5:prgmNAME:Ans` (5 or other input) for visual output.

Generates a list of `Ans` copies of `Ans`, then finds the product.

# Answer
> 1 votes
# Common Lisp, ~~59 42~~ 40 bytes

```
(lambda(x)(apply'*(fill(make-list x)x)))

```

Try it online!

# Answer
> 1 votes
## MATLAB/Octave, 23 bytes

```
@(n)(prod(n*ones(n,1)))

```

# Answer
> 1 votes
## Python, 32 bytes

```
f=lambda g,z=1:z>g or g*f(g,z+1)

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 2 bytes

```
G*

```

Try it online!

### Explanation

```
G*
G  # Do input - 1 times
 *  # Multiply with input

```

# Answer
> 1 votes
## Julia 0.6, 18 bytes

```
x->prod(x*ones(x))

```

# Answer
> 1 votes
# J, 5 bytes

```
*/@$~

```
* `$~` shapes the argument into a list with as many items as it is, eg, `3` becomes `3 3 3`.
* `@` pipes the result into...
* `*/` reduce by multiplication

Try it online!

# Answer
> 1 votes
# Ly, 16 bytes

```
ns<l1-[>l*<1-]>u

```

Being forced to use multiple stacks costs so many bytes...

Try it online!

# Answer
> 1 votes
# MAWP, 40 ~~25~~ 22 bytes

```
%@![~!~1A]%1A[1A~W~]%:

```

-15 from Dion's improved input methods. -3 after modifying first loop to happen x+1 times.

Try it!

### Explanation

```
%@                    Gets multi digit input
![~!~1A]%             x gets cloned x+1 times in the stack
1A[1A~W~]%:           multiplies top 2 numbers x-1 times

```

# Answer
> 1 votes
# Integral, 5 Bytes

```
v↕♦▼e

```

Try it!

## Explanation

```
v↕    Multiply two items of the stack, to be evaluated
  ♦   Swap the top two items
   ▼  Decrement
    e Evaluate ↕ that many times

```

# Answer
> 1 votes
## Google Sheets, 24

Input A1.

```
=DECIMAL(1&REPT(0,A1),A1

```

Is base conversion ok? If not, here's one at 26 (but it's really boring):

```
=PRODUCT(SEQUENCE(A1,1,A1,

```

# Answer
> 1 votes
# Java (JDK), 43+1 bytes

```
s->{int i=0,t=s;for(;++i<s;t*=s);return t;}

```

Try it online!

Overflows for `10`, so all `int`s need to be changed to `long` a the cost of +1. This has been done for the TIO link.

I didn't think I could beat the `IntStream` though!

# Answer
> 1 votes
# Keg, 9 bytes

```
¿(:;|:)∑*

```

Try it online!

I said I'd count Keg's victories over 1+ as victories for mawp, so it's 2-1 to mawp!

# Answer
> 1 votes
# Rust, 26 bytes

```
|x|(0..x).fold(1,|a,_|a*x)

```

Try it online!

# Answer
> 1 votes
# Factor \+ `math.unicode`, 18 bytes

```
[ dup <array> Π ]

```

Try it online!

```
        ! 5
dup     ! 5 5
<array> ! { 5 5 5 5 5 }
Π       ! 3125

```

# Answer
> 1 votes
# C++ (clang), 45 bytes

```
int e(int x,int i=0){return++i<x?x*e(x,i):x;}

```

Try it online!

# Answer
> 1 votes
# FunStack alpha, 14 bytes

```
Product Repeat

```

Try it at Replit!

### Explanation

```
        Repeat  Given one argument N, create a list of N copies of N
Product         Return the product of that list

```

# Answer
> 1 votes
# ReRegex, 55 bytes

```
#import math
(_+)p(_+)_/$1*($1p$2)/p_\b//#input
p#input

```

I/O as Unary \_'s.

## Explanation

Implements exponentiation by repeating the argument itself times. This is done by transforming, for instance `____p__` into `____*(____p_)`. Decrementing the right, and pulling the left out. Finally, any instance of `p_` has the p removed, as x^1==x.

Try it online!

# Answer
> 1 votes
# C (gcc) with `-lgmp`, 82 bytes

Uses GMP because everyone needs to be able to do `100**100`.

```
#import<gmp.h>
f(x,a,y)int*a;{mpz_init_set_ui(a,y=x);for(;--y;)mpz_mul_ui(a,a,x);}

```

Try it online!

# Answer
> 1 votes
# Arturo, 16 bytes

```
$=>[∏@.of:<=&]

```

Try it

# Answer
> 1 votes
# Julia 1.0, 17 bytes

```
!x=prod(_->x,1:x)

```

Try it online!

# Answer
> 1 votes
## Thunno 2, 3 bytes

```
⁻{×

```

Attempt This Online!

```
Wọp

```

Attempt This Online!

#### Explanation

```
⁻{×  # Implicit input
⁻    # Decrement the input
 {   # Repeat that many times:
  ×  #  Multiply TOS with input
     # Implicit output

```

```
Wọp  # Implicit input
W    # Wrap the input in a list
 ọ   # Repeat it input number of times
  p  # Product of this list
     # Implicit output

```

# Answer
> 0 votes
# PHP, 38 Bytes

```
for($p=1;$i++<$argn;)$p*=$argn;echo$p;

```

Try it online!

# Answer
> 0 votes
# MATL, 5 bytes

```
lyX"p

```

Try it online!

### Explanation

Example values with input `4`.

```
l    % Push 1
     % STACK: 1
y    % Implicit input. Duplicate from below
     % STACK: 4, 1, 4
X"   % Replicate along two dimensions. Gives a row vector
     % STACK: [4, 4, 4, 4]
p    % Product of array. Implicitly display.
     % STACK: 256

```

# Answer
> 0 votes
## QBIC, 12 bytes

```
:[a|q=q*a}?q

```

Explanation:

```
:   Get the integer
[a|     Start a FOR loop, for x iterations
q=q*a   Multiply q (starts out as 1) by our value, then store that in q
}       End loop
?q      Print q

```

# Answer
> 0 votes
## PowerShell, 34 33 bytes

```
,$n,$p=$args,1;1..$n|%{$p*=$n};$p

```

Try it online!

Previous version

```
,$n,$ofs=$args,'*';''+@($n)*$n|iex

```

# Answer
> 0 votes
# C (gcc), 34 bytes

```
i,k;f(x){for(i=k=x;--i;)x*=k;i=x;}

```

Try it online!

# Answer
> 0 votes
# Fourier, 19 bytes

```
1~YI~X(Y*X~Yi^~i)Yo

```

**Try it on FourIDE!**

Multiplies Y by the input X number of times and then outputs Y.

FYI, the standard way to do this would be

```
I~XPXo

```

Where `P` is the power function

# Answer
> 0 votes
# Python, 51 bytes

```
def f(x,i=0):i=i or x;return x*f(x,i-1)if i>1else x

```

A little bit more verbose than @xnor's clever way of `eval`, but uses recursion

# Answer
> 0 votes
# Groovy, 24 bytes

```
{a->r=1;a.times{r*=a};r}

```

# Answer
> 0 votes
# S.I.L.O.S, 56 bytes

```
readIO
x=i
readIO
a=i
b=1
lbla
a-1
b*x
if a a
printInt b

```

Try it online! Loops through repeated multiplication.

# Answer
> 0 votes
# Brain-Flak, 76 bytes

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

```

Try it online!

This is an extremely inefficient algorithm, so don't try inputs larger than 7.

Explanation:

```
#Duplicate the input
(({}))

#Make *n* copies of the input
{({}<(({}))>[()])}{}

#While the stack has more than one element on it,
{{}

  #Multiply the top two elements
  ({}<>)({<({}[()])><>({})<>}{}<><{}>)

  #Push stack-height minus one to keep the loop running
  ([][()])

#Endwhile
}

#Pop a zero off the main stack, implicitly display the number left on the stack
{}

```

# Answer
> 0 votes
# Aceto, 33 bytes

We have quite a bit of wasted space, so I'm sure we could get rid of a few more bytes.

```
=|
0*v
ds<

 MDL
 &_d
id!L
rDM@xp

```

The bottom half (except for the `xp`) reads the input, and puts it that many times on the stack, as an integer, i.e. '3' -\> \[3, 3, 3\]. I really need a builtin for that..

The top half calculates the product by swapping the top two elements, checking if the top element is zero, otherwise multiplying the top two elements, and so on. `xp` prints.

# Answer
> 0 votes
# Pari/GP, 16 bytes

```
n->prod(x=1,n,n)

```

Try it online!

# Answer
> 0 votes
# Java 9 JShell, 44 bytes

```
x->IntStream.range(0,x).reduce(1,(a,b)->a*x)

```

Try it online!

Notes:

* The imports are not included in the score since they are not required with the default JShell configuration (there are a number of packages imported by the default JShell startup script).
* Since TIO doesn't have JShell, a Java (OpenJDK 9) program is provided that demonstrates the function, but has been changed to use longs so that 10 to the tenth doesn't overflow, at the expense of one extra byte.

# Answer
> 0 votes
# Pyth, 9 bytes

```
u*GH*]QQ1

```

Try it online!

# Answer
> 0 votes
# Pyth, 4

This took me a while to figure out in pyth, but I finally got there:

```
*F*]

```

Try it online.

### Explanation

```
   ]Q     # create one-item list (of implicit input)
  *  Q    # repeat (implicit input) times
*F        # reduce list over multiplication

```

# Answer
> 0 votes
# tcl, 52

```
proc P n {incr p;time {set p [expr $p*$n]} $n;set p}

```

# demo

# Answer
> 0 votes
# tcl, 50

```
proc P n {time {lappend L $n} $n;expr [join $L *]}

```

# demo

# Answer
> 0 votes
# PowerShell, 36 bytes

```
$a="$args";$b=1;1..$a|%{$b=$b*$a};$b

```

Try it online!

# Answer
> 0 votes
# Python 2.7, 37 bytes

Full Program:

```
s,x=1,input();exec('s*=x;')*x;print s

```

Try it online!

# Answer
> 0 votes
# \>\<\>, 18 + 3 (-v flag) bytes

```
:l(?v:
=?v*>l1
n;>

```

Try it online!

-v flag to put our number on the stack allows for bigger numbers with little over head.

# Explination

```
:l(?v:

:l(     | Copies the stack top, adds the length of the stack then compares.
   ?v:  | Checks if the compare was true,
        |  if not then copy the stack top and loop, else move down.

=?v*>l1

    >l1 | Move the direction right, add the length of the stack, add 1 to the stack.
=?v*    | Compare the length of the stack to 1,
        |  if the stack is 1 item move down, else multiply the top 2 stack items.

n;>

n;>     | Moves the directions right, then prints the top stack item as a number then ends the program.

```

# Answer
> 0 votes
# Excel VBA, 34 Bytes

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

```
n=1:For i=1To[A1]:n=n*[A1]:Next:?n

```

## Interesting Version, 40 Bytes

Anonymous VBE immediate window function that takes input from Range `[A1]` and outputs `[A1^A1]` by method of worksheet manipulation to the VBE immediate window

```
[A1].Resize([A1],1)=[A1]:?[PRODUCT(A:A)]

```

# Answer
> 0 votes
# PHP, 44 bytes

```
<?=array_product(array_fill(1,$argn,$argn));

```

not the shortest solution; but it might trigger ideas for other languages.

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

# Answer
> 0 votes
# Pushy, 5 bytes

```
&tCP#

```

**Try it online!**

```
         \ Implicit: Input on stack                       [3]
&tC      \ Push (input - 1) extra copies of input         [3, 3, 3]
   P     \ Calculate product                              [3, 3, 3, 27]
    #    \ Output result                                  PRINT 27

```

# Answer
> 0 votes
# Rockstar, ~~71~~ 62 bytes

```
listen to N
X's0
P's1
while N-X
let X be+1
let P be*N-0

say P

```

Try it here (Code will need to be pasted in)

# Answer
> 0 votes
# Python 2, 37 bytes

```
lambda x:reduce(lambda a,b:a*b,[x]*x)

```

For Python 3, add

```
from functools import reduce

```

# Answer
> 0 votes
# Aussie++, 94 bytes

Not that there's an exponentiation builtin in the first place.

```
THE HARD YAKKA FOR f IS(x)<I RECKON a =1;I RECKON _ IS A WALKABOUT FROM[0TO x)a =a *x;BAIL a;>

```

Tested in commit 9522366. All whitespace included is necessary.

Just a straightforward golf of intPow from Math.aussie.

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