title: Am I a golfy array?

text:
# Question
Title: Am I a golfy array?
## Definition and Rules

A *golfy array* is an array of integers, where each element is *higher than or equal to* the arithmetic mean of all the previous elements. Your task is to determine whether an array of positive integers given as input is golfy or not.

## Test Cases & Example

For example the following array:

```
[1, 4, 3, 8, 6]

```

Is a golfy array, because each term is higher than the arithmetic mean of those preceding it. Let's work it out step-by-step:

```
Number -> Preceding elements -> Average -> Follows the rule?

1      -> []                 -> 0.0     -> 1 ≥ 0.0   (True)
4      -> [1]                -> 1.0     -> 4 ≥ 1.0   (True)
3      -> [1, 4]             -> 2.5     -> 3 ≥ 2.5   (True)
8      -> [1, 4, 3]          -> 2.(6)   -> 8 ≥ 2.(6) (True)
6      -> [1, 4, 3, 8]       -> 4.0     -> 6 ≥ 4.0   (True)

```

All the elements respect the condition, thus this is a golfy array. Note that for the purpose of this challenge, we will assume that the average of an empty list (`[]`) is `0`.

More test cases:

```
Input -> Output

[3]                 -> True
[2, 12]             -> True
[1, 4, 3, 8, 6]     -> True
[1, 2, 3, 4, 5]     -> True
[6, 6, 6, 6, 6]     -> True
[3, 2]              -> False
[4, 5, 6, 4]        -> False
[4, 2, 1, 5, 7]     -> False
[45, 45, 46, 43]    -> False
[32, 9, 15, 19, 10] -> False

```

---

**Note that this is *Puzzle 1* from *CodeGolf-Hackathon* and is also posted on Anarchy Golf (that one is broken) - *Reposted* by histocrat, but I am the original author on both sites, and thus allowed to repost them here.**

# Answer
# Python 2, 37 bytes

```
def g(a):sum(a)>len(a)*a.pop()or g(a)

```

Try it online!

Outputs via exit code: crashes (exit code 1) for golfy arrays, just exits with exit code 0 for non-golfy arrays. ovs and Jonathan Frech saved 3 bytes.

### Python 2, 44 bytes

```
f=lambda a:a and sum(a)<=len(a)*a.pop()*f(a)

```

Try it online!

A more traditional variant, which returns `True` for golfy arrays, else `False`. Jonathan Frech saved 2 bytes.
> 14 votes

# Answer
# Jelly, ~~6~~ 5 bytes

```
<ÆmƤE

```

Try it online!

### How it works

```
<ÆmƤE  Main link. Argument: A (integer array)

 ÆmƤ   Compute the arithmetic means (Æm) of all prefixes (Ƥ) of A.
<      Perform element-wise comparison. Note that the leftmost comparison always
       yields 0, as n is equal to the arithmetic mean of [n].
    E  Test if all elements of the resulting array are equal, which is true if and
       only if all comparisons yielded 0.

```
> 12 votes

# Answer
## JavaScript (ES6), ~~33~~ 32 bytes

```
a=>a.some(e=>e*++i<(s+=e),s=i=0)

```

Code also works on negative values such as`[-3, -2]`. Returns `false` for a golfy array, `true` for other arrays. Edit: Saved 1 byte thanks to @JustinMariner.
> 5 votes

# Answer
## Wolfram Language (Mathematica), 35 bytes

```
Max[Accumulate@#-Range@Tr[1^#]#]>0&

```

Try it online!

Outputs `False` for golfy arrays and `True` otherwise.
> 4 votes

# Answer
# MATL, ~~9~~ 8 bytes

```
tYstf/<a

```

Outputs `0` for golfy arrays, `1` otherwise.

**Try it online!**

### Explanation

Consider input `[1, 4, 3, 8, 6]`.

```
t    % Implicit input. Duplicate
     % STACK: [1, 4, 3, 8, 6], [1, 4, 3, 8, 6]
Ys   % Cumulative sum
     % STACK: [1, 4, 3, 8, 6], [1, 5, 8, 16, 22]
t    % Duplicate
     % STACK: [1, 4, 3, 8, 6], [1, 5, 8, 16, 22], [1, 5, 8, 16, 22]
f    % Find: indices of nonzeros. Gives [1, 2, ..., n], where n is input size
     % STACK: [1, 4, 3, 8, 6], [1, 5, 8, 16, 22], [1, 2, 3, 4, 5]
/    % Divide, element-wise
     % STACK: [1, 4, 3, 8, 6], [1, 2.5, 2.6667, 4, 4.4]
<    % Less than?, element-wise
     % STACK: [0, 0, 0, 0, 0]
a    % Any: true if and only there is some nonzero. Implicit display
     % STACK: 0

```
> 4 votes

# Answer
# Haskell, ~~53~~ ~~50~~ 48 bytes

```
and.(z(<=).scanl1(+)<*>z(*)[1..].tail)
z=zipWith

```

Try it online!

*Edit:* -3 bytes thanks to Zgarb!

**Explanation**

The above point-free version is equivalent to the following program:

```
f s = and $ zipWith(<=) (scanl1(+)s) (zipWith(*)[1..](tail s))

```

Given an input `s=[1,4,3,8,6]`, `scanl1(+)s` computes the prefix sums `[1,5,8,16,22]` and `zipWith(*)[1..](tail s)` drops the first element and multiplies all other elements with their index: `[4,6,24,24]`. The list is now *golfy* if pairwise the prefix sums are smaller or equal to the elements times index, which can be checked by zipping both lists with `(<=)` and checking that all results are `True` with `and`.
> 4 votes

# Answer
# C# (Visual C# Compiler), 71 + 18 = 89 bytes

```
x=>x.Select((n,i)=>new{n,i}).Skip(1).All(y=>x.Take(y.i).Average()<=y.n)

```

additional 18 bytes for `using System.Linq;`

Try it online!
> 3 votes

# Answer
# C (gcc), ~~62~~ ~~60~~ 62 bytes

* Removed two superfluous parentheses.
* Added two bytes to fix function's reusability (`b=`).

```
f(A,S,k,b)int*A;{for(S=k=b=0;*A;S+=*A++)b+=!(S<=*A*k++);b=!b;}

```

Try it online!
> 3 votes

# Answer
# 05AB1E, 5 bytes

```
ηÅA÷W

```

Try it online!

Extensive help from Dennis and Adnan got to this reduced version. Also a bug was fixed to make this possible, thanks again you guys. I take little credit for this answer.

---

# 05AB1E, 10 bytes

```
ηεÅA}ü.S_P

```

Try it online!

---

~~Long because `DgsO/` is the equivalent of "mean" in 05AB1E.~~

Apparently `ÅA` is arithmetic mean.
> 3 votes

# Answer
# APL (Dyalog), 10 bytes

This is an anonymous tacit prefix function (called a monadic train in APL terms).

```
∧/⊢≥+\÷⍳∘≢

```

Try all the test cases on TIO!

*Is it*

`∧/` all-true that

the elements

are greater than or equal to

`+\` the cumulative sums

`÷` divided by

the integers 1 through

the

number of elements

*?*
> 3 votes

# Answer
# APL (Dyalog), 15 bytes

```
∧/⊢≥((+/÷≢)¨,\)

```

Try it online!

**How?**

```
            ,\  all prefixes
           ¨    for each
      +/÷≢      calculate arithmetic mean
  ⊢≥            element wise comparison
∧/              logically and the result

```
> 2 votes

# Answer
# PowerShell, 60 bytes

```
param($a)$o=1;$a|%{$o*=$_-ge($a[0..$i++]-join'+'|iex)/$i};$o

```

Try it online!

Takes input as a literal array (e.g., `@(1, 4, 3, 8, 6)`) into `$a`. Sets our `$o`utput variable to be `1`. Then loops through `$a`. Each iteration, we're (ab)using PowerShell's implicit casting to `*=` the result of a Boolean comparison against our `$o`utput. The Boolean is whether the current value `$_` is `-g`reater-than-or-`e`qual to the previous terms `$a[0..$i++]` added together (`-join'+'|iex`) divided by how many terms we've already seen `$i`. So, if any step along the way is false, then `$o` will get multiplied by `0`. Otherwise, it will remain `1` throughout.

We then simply place `$o` onto the pipeline and output is implicit. `1` for truthy and `0` for falsey.
> 2 votes

# Answer
# Perl 5, 27 +2 (-ap) bytes

```
$_=!grep$_*++$n<($s+=$_),@F

```

Try It Online
> 2 votes

# Answer
# Matlab and Octave, ~~41~~ 36 bytes

*5 bytes saved thx to Luis Mendo*

```
all([a inf]>=[0 cumsum(a)./find(a)])

```

Try it online!
> 2 votes

# Answer
# C# (.NET Core), 74 bytes

```
x=>{for(int i=1,s=0;i<x.Count;)if(x[i]<(s+=x[i-1])/i++)return 0;return 1;}

```

Try it online!

Returns 0 for false and 1 for true.

3 Bytes longer than core of chryslovelaces answer. But in total several Bytes shorter because my variant doesn't need any `using` statements.
> 2 votes

# Answer
# Cubix, 35 bytes

```
/I?/\+psu0^.\)*sqs;-\;;U;O1.....?@^

```

Try it online!

Not the most efficient use of space (6 no-ops in the code) Produces no output for a golfy array, `1` for a not-golfy array.

Expands to the following cube:

```
      / I ?
      / \ +
      p s u
0 ^ . \ ) * s q s ; - \
; ; U ; O 1 . . . . . ?
@ ^ . . . . . . . . . .
      . . .
      . . .
      . . .

```

Explanation forthcoming, but it basically ports something like Luis Mendo's MATL answer or Dennis' Julia answer.

Watch it run!
> 2 votes

# Answer
# SQL (MySQL), 68 bytes

```
select min(n>=(select ifnull(avg(n),1)from t s where s.i<t.i))from t

```

Try it online!

Returns **1** for golfy arrays, and **0** otherwise. Takes input from a named table, `t`. In order to create `t`, run:

```
CREATE TABLE t(i SERIAL,n INT)

```

and to load the values:

```
truncate table t;insert into t(n)values(3),(2);

```
> 2 votes

# Answer
# Husk, 5 bytes

```
Λ<mAḣ

```

Try it online!

Modification of Mr. Xcoder's solution from the linked repository.

-1, a sweet victory using `all2`!

# Husk, <sup>~~8~~</sup> 7 bytes

```
ΛΓ·<Aṫ↔

```

Try it online!

Took me long enough to use `Γ` here.(more than a year!)
> 2 votes

# Answer
# Factor, 26 bytes

```
[ dup cum-mean v>= vall? ]

```

Try it online!

## Explanation

Factor has some pretty great words for this.

```
         ! { 1 4 3 8 6 }
dup      ! { 1 4 3 8 6 } { 1 4 3 8 6 }
cum-mean ! { 1 4 3 8 6 } { 1 2+1/2 2+2/3 4 4+2/5 }
v>=      ! { t t t t t }
vall?    ! t

```
> 2 votes

# Answer
# Python 2, 52 bytes

```
lambda A:all(k*j>=sum(A[:j])for j,k in enumerate(A))

```

Try it online!

# Python 2, ~~50~~ ~~48~~ ~~44~~ 42 bytes

* Saved two bytes by inlining and using `and`.
* Saved two bytes thanks to Mr. Xcoder by chaining assignment `S=k=0`.
* Saved two bytes by using `or` and the comparison's boolean value as `k`'s increment value.
* Saved two bytes thanks to ovs; raising a `NameError` by using an undefined variable instead of a `ZeroDivisionError`.

```
S=k=0
for j in input():k+=S<=j*k or J;S+=j

```

Try it online!
> 1 votes

# Answer
# Ruby, 30 bytes

```
->a{0until a.pop*a.size<a.sum}

```

Try it online!

Inspired by Lynn's answer. Throws `NoMethodError` for golfy, returns `nil` otherwise.
> 1 votes

# Answer
# q/kdb+, 14 bytes

**Solution:**

```
min x>=avgs x:

```

**Examples:**

```
q)min x>=avgs x:1 4 3 8 6
1b                           / truthy
q)min x>=avgs x:4 2 1 5 7
0b                           / falsey

```

**Explanation:**

Fairly simple with the `avgs` built-in:

```
min x>=avgs x: / solution
            x: / store input in variable x
       avgs    / calculate running averages
    x>=        / array comparison, x greater than running average
min            / take minimum of list of booleans

```
> 1 votes

# Answer
# Julia 0.6, 29 bytes

```
!x=any(find(x).*x.<cumsum(x))

```

Returns *false* or *true*.

Try it online!
> 1 votes

# Answer
# Add++, 54 bytes

```
D,g,@@#,BFB
D,k,@,¦+AbL/
D,f,@,dbLR$€g€k0b]$+ABcB]£>ª!

```

Try it online!

### Unoriginal version, 30 bytes

```
D,f,@,¬+AbLRBcB/@0@B]ABcB]£>ª!

```

Try it online!

Both output **1** for golfy arrays and **0** otherwise

## How they work

The first version was created by me, without checking any other solutions. The second was inspired by Dennis' comment, so I'm less happy with it.

### The first version

Here, we define our main function \\$f\\$ that computes the *golfiness* of our input array, \\$A\\$. First, we need to yield the suffixes of \\$A\\$, which is done by first generating the range \\$B := \[1, ... \vert{A}\vert\]\\$, where \\$\vert{A}\vert\\$ denotes the length of \\$A\\$. This is done with the code `dbLR$`, which leaves \\$\[B, A\]\\$ as the stack. We then iterate the dyadic function \\$g\\$ over these two lists. Being dyadic, the function binds its left argument as \\$A\\$ for each iterated element. It then iterates over the range \\$B\\$, which each element from \\$B\\$ being the right argument provided to \\$g\\$. \\$g\\$ is defined as

```
D,g,@@#,BFB

```

which is a dyadic function (i.e. takes \\$2\\$ arguments), and pushes its arguments to the stack in reversed order (`#`) before execution. `BF` then flattens the two arguments. We'll assume that the arguments are \\$A\\$ and \\$e \in x\\$. This leaves the stack as \\$\[...A, e\]\\$, where \\$...\\$ represents an array splat. Finally, `B` takes the first \\$e\\$ elements of \\$A\\$ and returns a list containing those elements.

*Note* : The function names \\$g\\$ and \\$k\\$ aren't chosen randomly. If the commands given to an operator (such as ) doesn't currently have a function (which `g` and `k` don't), then the named functions are searched for a matching function. This saves \\$2\\$ bytes, as normally the function would have to wrapped in `{...}` to be recognised as a user-defined function. At the time of writing, the currently unused single byte commands are `I`, `K`, `U`, `Y`, `Z`, `g`, `k`, `l`, `u` and `w`.

When \\$g\\$ is applied over the elements of a range \\$x\\$, this returns a list of prefixes for \\$A\\$. We then map our second helper function \\$k\\$ over each of these prefixes. \\$k\\$ is defined as

```
D,k,@,¦+AbL/

```

which is the standard implementation of the arithmetic mean. `¦+` calculates the sum of the argument, `AbL` calculates its length, then `/` divides the sum by the length. This calculates the arithmetic mean of each prefix, yielding a new array, \\$C\\$.

Unfortunately, \\$C\\$ contains the mean of \\$A\\$ as its final element, and does not include the mean of the empty list, \\$0\\$. Therefore, we would have to remove the final element, and prepend a \\$0\\$, but popping can be skipped, saving two bytes, for reasons explained in a second. Instead, we push \\$\[0\]\\$ underneath \\$C\\$ with `0b]$`, then concatenate the two arrays forming a new array, \\$C^+\\$.

Now, we need to check each element as being less than its corresponding element in \\$A\\$. We push \\$A\\$ once again and zip the two arrays together with `ABcB]`. This is the reason we don't need to pop the final element: `Bc` is implemented with Python's `zip` function, which truncates the longer arrays to fit the length of the shortest array. Here, this removes the final element of \\$C^+\\$ when creating the pairs.

Finally, we starmap \\$p \in A, q \in C^+; p \< q \equiv \neg(p \ge q)\\$ over each pair \\$p, q\\$ to obtain an array of all \\$0\\$s if the array is golfy, and array containing at least a single \\$1\\$ if otherwise. We then check that all elements are falsey i.e. are equal to \\$0\\$ with `ª!` and return that value.

### The second version

This takes advantage of Dennis' approach to remove \\$24\\$ bytes, by eliminating the helper functions. Given our input array of \\$A\\$, we first compute the cumulative sums with `¬+`, i.e the array created from \\$\[A\_0, A\_0+A\_1, A\_0+A\_1+A\_2, ..., A\_0+...+A\_i\]\\$. We then generate Jelly's equivalent of `J` (*indicies*), by calculating the range \\$B := \[1 ... \vert{A}\vert\]\\$ where \\$\vert{A}\vert\\$ once again means the length of the array.

Next, we divide each element in \\$A\\$ by the corresponding index in \\$B\\$ with `BcB/` and prepend \\$0\\$ with `@0@B]`. This results in a new array, \\$C^+\\$, defined as

$$C^+ := \[0, A\_0, \frac{A\_0+A\_1}{2}, \frac{A\_0+A\_1+A\_2}{3}, ..., \frac{A\_0+...+A\_i}{i+1}\]$$

The final part is identical to the first version: we push and zip \\$A\\$ with \\$C^+\\$, then starmap inequality over each pair before asserting that all elements in the resulting array were falsy.
> 1 votes

# Answer
# , ~~38~~ 34 bytes

```
function(x)any(cumsum(x)/seq(x)>x)

```

Try it online!
> 1 votes

# Answer
# Vyxal, 5 bytes

```
Kvṁ<≈

```

Try it Online!

Porting jelly got me feeling like yeet.

## Explained

```
Kvṁ<≈
K     # prefixes of the input
 vṁ   # the mean of each of those prefixes
   <  # is the input less than each of those means?
    ≈ # and is everything the same?

```
> 1 votes

# Answer
# Desmos, 55 bytes

```

f(l)=\sum_{n=2}^{l.\length}\{l[1...n-1].\mean>l[n],0\}

```

Outputs `0` for golfy array, and a positive integer otherwise.

Try It On Desmos!

Try It On Desmos! - Prettified
> 1 votes

# Answer
# Scala, 109 bytes

Golfed version, try it online!

```
def f(a:List[Int]):Boolean={a match{case Nil=>true;case _=>a.sum<=(a.length*a.last*(if(f(a.init))1 else 0))}}

```

Ungolfed version

```
object Main {
  def f(a: List[Int]): Boolean = {
    a match {
      case Nil => true
      case _ => a.sum <= (a.length * a.last * (if(f(a.init)) 1 else 0))
    }
  }

  def main(args: Array[String]): Unit = {
    assert(f(List(3)) == true)
    assert(f(List(2, 12)) == true)
    assert(f(List(1, 4, 3, 8, 6)) == true)
    assert(f(List(1, 2, 3, 4, 5)) == true)
    assert(f(List(6, 6, 6, 6, 6)) == true)
    assert(f(List(3, 2)) == false)
    assert(f(List(4, 5, 6, 4)) == false)
    assert(f(List(4, 2, 1, 5, 7)) == false)
    assert(f(List(45, 45, 46, 43)) == false)
    assert(f(List(32, 9, 15, 19, 10)) == false)

    println("No assertion errors.")
  }
}

```
> 1 votes

# Answer
# Pyth, 11 10 bytes

-1 byte thanks to Mr. Xcoder

```
.A.egb.O<Q

```

Try it online!
> 0 votes

# Answer
# Java (OpenJDK 8), 96 bytes

I know it's not a good golfing language, but I still gave it a go!

Input array as first argument of comma separated ints to test.

Returns 1 for true, 0 for false.

```
a->{int i=1,j,r=1,s=0;for(;i<a.length;i++,s=0){for(j=0;j<i;s+=a[j++]);r=s/i>a[i]?0:r;}return r;}

```

Try it online!
> 0 votes

# Answer
# Java 7, 100 bytes

Golfed:

```
int g(int[]a){int i=1,m=0,s=m,r=1;for(;i<a.length;){s+=a[i-1];m=s/i;r-=a[i++]<m&&r>0?1:0;}return r;}

```

Ungolfed:

```
int golfy(int[]a)
{
    int i = 1, m = 0, s = m, r = 1;
    for (; i < a.length;)
    {
        s += a[i-1];
        m = s / i;
        r -= a[i++] < m && r>0? 1 : 0;
    }
    return r;
}

```

Try it online

Returns 0 for ungolfy and 1 for golfy arrays. Slightly longer than java 8 answer.
> 0 votes

# Answer
# PHP, 44 bytes

```
while($n=$argv[++$i])$n<($s+=$n)/$i&&die(1);

```

takes input from command line arguments, exits with `0` (ok) for a golfy array, with `1` else.

Run with `-nr` or try it online.
> 0 votes

# Answer
# J, 19 bytes

```
[:*/[>:[:}:0,+/\%#\

```

`+/\ % #\` averages of the prefixes: `#\` produces 1..n

`}:0,` add 0 to the beginning and remove the last

`[>:` is the original list element by element \>= to the shifted list of averages?

`*/` are *all* the elements greater, ie, the previous list is all `1`s?

Try it online!
> 0 votes

# Answer
# AWK, 39 bytes

```
{for(;i++*$i>=s&&i<=NF;s+=$i);$0=i>NF}1

```

Try it online!

Note that the TIO link has 5 extra bytes `i=s=0` to allow for multi-line input.
> 0 votes

# Answer
# Japt, 10 bytes

Came up with two 10 byte solutions, can't seem to improve on that.

```
eÈ¨U¯Y x÷Y

```

Try it

---

## Explanation

```
               :Implicit input of array U
eÈ             :Is every element, at 0-based index Y
  ¨            :Greater than or equal to
   U¯Y         :U sliced from index 0 to index Y
        ÷Y     :Divide each element by Y
       x       :Reduce by addition

```

---

## Alternative

```
eÈ*°Y¨(T±X

```

Try it

```
               :Implicit input of array U
eÈ             :Is every element X (at 0-based index Y)
  *°Y          :Multiplied by Y incremented by 1
     ¨         :Greater than or equal to
      (T±X     :T (initially 0) incremented by X

```
> 0 votes

# Answer
# Kotlin, 51 bytes

```
foldIndexed(0,{i,s,e->if(s<0||s>e*i)-1 else s+e})>0

```

Try it online!

(69 bytes with entire declaration of extension function)
```
fun List<Int>.g()=foldIndexed(0,{i,s,e->if(s<0||s>e*i)-1 else s+e})>0

```
> 0 votes

# Answer
# Arturo, 33 bytes

```
$=>[0v:0some?&'x['v+x x<v//<=1+]]

```

Try it

Returns `false` for true and `true` for false.

```
$=>[             ; a function, assign input to &
    0            ; push 0 to the stack, this represents the current count of elements
    v:0          ; assign 0 to v, this represents the running average
    some?&'x[    ; is there any x in the input that...
        'v+x     ; add x to v in place
        1+       ; add 1 to value on top of the stack
        <=       ; duplicate top of stack
        x<v//    ; is x less than v divided by top of stack?
    ]            ; end some?
]                ; end function

```
> 0 votes

# Answer
# Thunno 2, 5 bytes

```
ƒ€m<ạ

```

Try it online!

Port of Dennis's Jelly answer.

#### Explanation

```
ƒ€m<ạ  # Implicit input
ƒ      # Prefixes of the input
 €m    # Mean of each prefix
   <   # Input is less than this?
    ạ  # All equal (all are 0?)
       # Implicit output

```
> 0 votes

---
Tags: code-golf, number, arithmetic, array, decision-problem
---


title: Print the tetration

text:
# Question
Title: Print the tetration
> Tetration, represented as \\${}^ba\\$, is repeated exponentiation. For example, \\${}^32\\$ is \\$2^{2^2}\\$, which is \\$16\\$.

Given two numbers \\$a\\$ and \\$b\\$, print \\${}^ba\\$.

## Test cases

```
1 2 -> 1
2 2 -> 4
5 2 -> 3125
3 3 -> 7625597484987
etc.

```

Scientific notation is acceptable.

Remember, this is , so the code with the smallest number of bytes wins.

# Answer
# Dyalog APL, 3 bytes

```
*/⍴

```

TryAPL.

## Explanation

```
*/⍴  Input: b (LHS), a (RHS)
  ⍴  Create b copies of a
*/   Reduce from right-to-left using exponentation

```
> 16 votes

# Answer
# J, ~~5~~ 4 bytes

```
^/@#

```

This is literally the definition of tetration.

## Usage

```
   f =: ^/@#
   3 f 2
16
   2 f 1
1
   2 f 2
4
   2 f 5
3125
   4 f 2
65536

```

## Explanation

```
^/@#  Input: b (LHS), a (RHS)
   #  Make b copies of a
^/@   Reduce from right-to-left using exponentation

```
> 10 votes

# Answer
## Haskell, 19 bytes

```
a%b=iterate(a^)1!!b

```

Iterates exponentiating starting at `1` to produce the list `[1,a,a^a,a^a^a,...]`, then take the `b`'th element.

Same length directly:

```
a%0=1;a%b=a^a%(b-1)

```

Point-free is longer:

```
(!!).(`iterate`1).(^)

```
> 9 votes

# Answer
## Python, 30 bytes

```
f=lambda a,b:b<1or a**f(a,b-1)

```

Uses the recursive definition.
> 9 votes

# Answer
# Mathematica, 16 bytes

```
Power@@Table@##&

```

# Explanation

```
Table@##

```

Make b copies of a.

```
Power@@...

```

Exponentiation.
> 9 votes

# Answer
# Jelly, 4 bytes

```
x*@/

```

Try it online! or verify all test cases.

### How it works

```
x*@/  Main link. Arguments: a, b

x     Repeat [a] b times.
 *@/  Reduce the resulting array by exponentation with swapped arguments.

```
> 6 votes

# Answer
# Python, 33 bytes

```
lambda a,b:eval('**'.join([a]*b))

```

This evaluates to an unnamed function, that takes the string representation of a number and a number. For example:

```
>>> f=lambda a,b:eval('**'.join([a]*b))
>>> f('5',2)
3125
>>>

```

If mixing input formats like this does not count, there is also this 38 byte version:

```
lambda a,b:eval('**'.join([str(a)]*b))

```
> 5 votes

# Answer
# 05AB1E, ~~9~~ ~~4~~ 2 bytes

*-2 thanks to ovs.*

```
Gm

```

Try it online! Beats all other answers

```
Gm  # full program
G   # for N in [1, 2, 3, ...,
    # ..., implicit input...
G   # ...minus 1]...
 m  # push...
    # implicit input...
 m  # to the power of...
    # implicit input...
    # (implicit) or top of stack if not first iteration
    # implicit output

```
> 4 votes

# Answer
# Perl, 19 bytes

Includes +1 for `-p`

Give numbers on separate lines on STDIN

```
tetration.pl
2
3
^D

```

`tetration.pl`

```
#!/usr/bin/perl -p
$_=eval"$_**"x<>.1

```
> 3 votes

# Answer
# R, 39 bytes

Recursive function:

```
f=function(a,b)ifelse(b>0,a^f(a,b-1),1)

```
> 3 votes

# Answer
# Factor, ~~29~~ 26 bytes

```
[ 1 rot [ dupd ^ ] times ]

```

Try it online!

*-3 thanks to @Bubbler*
> 3 votes

# Answer
# Element, 11 bytes

```
__2:':1[^]`

```

Try it online!

This is just "straightforward" exponentiation in a loop.

```
__2:':1[^]`
__              take two values as input (x and y)
  2:'           duplicate y and send one copy to the control stack
     :          make y copies of x
      1         push 1 as the initial value
       [ ]      loop y times
        ^       exponentiate
          `     print result

```
> 2 votes

# Answer
# JavaScript (ES7), 24 bytes

```
f=(a,b)=>b?a**f(a,b-1):1

```

The ES6 version is 33 bytes:

```
f=(a,b)=>b?Math.pow(a,f(a,b-1)):1

```
> 2 votes

# Answer
# dc, ~~35~~ 29 bytes:

```
?dsdsa?[ldla^sa1-d1<b]dsbxlap

```

Here is my first complete program in `dc`.
> 2 votes

# Answer
# GameMaker Language, ~~52~~ 50 bytes

```
d=a=argument0;for(c=1;c<b;c++)d=power(a,d)return d

```
> 2 votes

# Answer
# PHP, 51 Bytes

```
for($b=$p=$argv[1];++$i<$argv[2];)$p=$b**$p;echo$p;

```
> 2 votes

# Answer
# Perl, 40 bytes

```
map{$a=$ARGV[0]**$a}0..$ARGV[1];print$a;

```

Accepts two integers as input to the function and outputs the result
> 1 votes

# Answer
# Actually, 6 bytes

```
n`ⁿ)`Y

```

Try it online!

Input is taken as `b\na` (`\n` is a newline)

Explanation:

```
n`ⁿ)`Y
n       a copies of b
 `ⁿ)`Y  while stack changes between each call (fixed-point combinator):
  ⁿ       pow
   )      move top of stack to bottom (for right-associativity)

```
> 1 votes

# Answer
# CJam, 9 bytes

```
q~)*{\#}*

```

Try it online!

### Explanation

```
q~          e# Take input (array) and evaluate
  )         e# Pull off last element
   *        e# Array with the first element repeated as many times as the second
    {  }*   e# Reduce array by this function
     \#     e# Swap, power

```
> 1 votes

# Answer
# Wonder, 21 bytes

```
f\@@[#0?^#1f#1-#0 1?1

```

Uses the recursive approach. Usage:

```
f\@@[#0?^#1f#1-#0 1?1];f 2 3

```

# Bonus solution, 22 bytes

```
@@:^ -#0 1(genc ^#1)#1

```

A slightly unconventional approach. Usage:

```
t\@@+>#[^;#1]tk -#0 1rpt#1;t 2 3

```

More readable:

```
@@
  iget
    - #0 1
    (genc ^#1) #1

```

Assuming `a^^b`:

Generates an infinite list of tetrated `a`; for `a=2`, this list would look something like `[2 4 16 65536...]`. Then indexes at `b-1` because Wonder is zero-indexed.
> 1 votes

# Answer
# Flurry `-nii`, 14 bytes

```
{}{{}({})}{{}}

```

Try it online!

Takes two numbers `a b` from stdin, and outputs as the return value.

### How it works

It works basically like xnor's Haskell answer: repeat `(a^)` `b` times to 1. `a` is left on the stack, so that it can be referenced in each iteration.

```
// In Church numeral, x a → a^x
main = b power_of_a 1

power_of_a = \x. x a
           = \x. x (push pop)  // assumes a is on the top of the stack,
                               // pops and takes its value and pushes it back

```
> 1 votes

# Answer
# GolfScript, 9 bytes

```
~])*{\?}*

```

Try it online!

```
~]          # Put a and b in an array
  )         # Remove b from the array
   *        # Make b copies of a
    {  }*   # Execute this block for each number in the array
     \?     # Exponentiation

```

Just `{?}` would be `(3^3)^3` instead of `3^(3^3)`.
> 1 votes

# Answer
# Vyxal `r`, 4 bytes

This is lyxal's solution

```
‹(⁰e

```

Try it Online!

```
‹(⁰e
‹     Decrement b
 (  ) For loop (second parentheses is implicit) using b-1
  ⁰   Push a
   e  And raise it to the power of the accumulator (initially a)

```

## Vyxal, ~~6~~ 5 bytes

Saved 1 byte thanks to lyxal

```
ʁ•⁽eḭ

```

Try it Online!

This one is a worse solution. `a` is inputted as a singleton list.

```
ʁ•λe;ḭ
ʁ      Make a range [0,b) (only the length of the range matters (b))
 •     Reshape [a] to that (make a list of b a's)
     ḭ Reduce from the right
  λe;  using exponentiation

```
> 1 votes

# Answer
# Red, ~~38~~ ~~26~~ 37 bytes

*Thanks to @9214 for telling me about the `loop` command for -12 bytes.*

*+11 bytes to fix invalidities brought out by @Bubbler.*

```
func[a b][x: a loop b - 1[x: a ** x]]

```

Try it online!
> 1 votes

# Answer
# K (ngn/k), 7 bytes

```
(*/#)/#

```

Try it online!

Takes two inputs in the order of `[hyperexponent; base]` and returns the result.

K does not have exponentiation built-in, so I simulate `n^m` with "product `*/` of m copies `#` of n" instead. Tetration is basically the same, in the sense that it is a fold by exponentiation. K's fold is left to right, and `*/#` accepts `[exponent; base]`, so the direction of exponentiation is correctly `y^(y^(y^...))`.

Although it does not use exponentiation built-in, it fails to solve this challenge because `4^(4^4)` is way too big to handle with built-in integer sizes.
> 1 votes

# Answer
# Pyth, 6 bytes

```
u^QGE1

```

Try it online.

### Explanation

```
          (implicit: input a to Q)
     1    Start from 1.
u   E     b times,
 ^GQ      raise the previous number to power a.

```
> 0 votes

# Answer
## Minkolang 0.15, ~~12~~ 11 bytes

```
nnDI1-[;]N.

```

Try it here!

### Explanation

```
nn             Read two integers from input
  D            Pop top of stack and duplicate next element that many times
   I1-         Push length of stack, minus 1
      [        Pop top of stack and repeat for loop that many times
       ;       Pop b, a and push a^b
        ]      Close for loop
         N.    Output as number and stop.

```
> 0 votes

# Answer
## Racket 51 bytes

```
(define ans 1)(for((i b))(set! ans(expt a ans)))ans

```

Ungolfed:

```
(define (f a b)
  (define ans 1)
  (for((i b))
    (set! ans
          (expt a ans)))
  ans)

```

Testing:

```
(f 1 2)
(f 2 2)
(f 5 2)
(f 3 3)

```

Output:

```
1
4
3125
7625597484987

```
> 0 votes

# Answer
# Scala, 45 bytes

```
Seq.fill(_:Int)(_:Double)reduceRight math.pow

```

Ungolfed:

```
(a:Int,b:Double)=>Seq.fill(a)(b).reduceRight(math.pow)

```

Build a sequence of `a`s with `b` elements, and apply `math.pow` from right to left.
> 0 votes

# Answer
# TI-Basic, 19 bytes

```
Prompt A,B
A
For(C,2,B
A^Ans
End

```
> 0 votes

# Answer
# Java 7, ~~71~~ 57 bytes

```
double c(int a,int b){return b>0?Math.pow(a,c(a,b-1)):1;}

```

**Ungolfed & test code:**

Try it here.

```
class M{
  static double c(int a, int b){
    return b > 0
            ? Math.pow(a, c(a, b-1))
            :1;
  }

  public static void main(String[] a){
    System.out.println(c(1, 2));
    System.out.println(c(2, 2));
    System.out.println(c(5, 2));
    System.out.println(c(3, 3));
  }
}

```

**Output:**

```
1.0
4.0
3125.0
7.625597484987E12

```
> 0 votes

# Answer
# C, 50 bytes

```
double t(int x,int n){return n?pow(x,t(x,n-1)):1;}

```

Straightforward from the definition of Tetration.
> 0 votes

# Answer
**Axiom 70 bytes**

```
l(a,b)==(local i;i:=1;r:=a;repeat(if i>=b then break;r:=a^r;i:=i+1);r)

```

this less golfed

```
l(a,b)==
  local i
  i:=1;r:=a;repeat(if i>=b then break;r:=a^r;i:=i+1)
  r

(3) ->  [l(1,2),l(2,2),l(5,2),l(3,3),l(4,3)]

     (3)
     [1, 4, 3125, 7625597484987,
      13407807929942597099574024998205846127479365820592393377723561443721764030_
       0735469768018742981669034276900318581864860508537538828119465699464336490_
       06084096
       ]
                                                   Type: List PositiveInteger

```
> 0 votes

# Answer
# Bash, 50 bytes

(within the bounds of bash integer data type)

**Golfed**

```
E() { echo $(($(printf "$1**%.0s" `seq 1 $2`)1));}

```

**Explanation**

Build expression with printf, e.g. E 2 5:

```
  2**2**2**2**2**1

```

then use bash built-in arithmetic expansion to compute the result

**Test**

```
E 1 2
1

E 2 2
4

E 5 2
3125

E 3 3
7625597484987

```
> 0 votes

# Answer
## Powershell, 68 Bytes

```
filter p ($a){[math]::Pow($a,$_)};iex (,$args[0]*$args[1]-join"|p ")

```

This is the shortest of the three approaches I tried, not that great overall though, i'm 100% sure there's a shorter approach but the few things I tried somehow ended up with slightly more bytes.

```
PS C:\++\golf> (1,2),(2,2),(5,2),(3,3) | % {.\sqsq $_[0] $_[1]}
1
4
3125
7625597484987

```

Sadly Powershell has no built-in `^` or `**` operator, or it would be a clean 32/33 byte answer, i.e.

`iex (,$args[0]*$args[1]-join"^")`
> 0 votes

# Answer
## Clojure, 56 bytes

```
(fn[a b](last(take a(iterate #(apply *(repeat % b))b))))

```

Maybe there is a shorter way via `apply comp`?
> 0 votes

# Answer
# Funky, 27 bytes

```
f=(a,b)=>(b<2)?a:a^f(a,b-1)

```

Try it online!
> 0 votes

# Answer
# Thunno 2 `t`, 3 bytes

```
ọƲ@

```

Try it online!

#### Explanation

```
ọƲ@  # Implicit input
ọ    # Repeat [a] b times
 Ʋ   # Reduce the list by:
  @  #  Swapped exponentiation
     # Implicit output

```
> 0 votes

# Answer
# Raku, 16 bytes

```
{[**] $^a xx$^b}

```

Try it online!

`$^a` and `$^b` are the arguments to this anonymous function. `$^a xx $^b` is a list of the first argument replicated a number of times given by the second argument. `[**]` reduces that list with the exponentiation operator. The reduction respects the right-associativity of the operator.
> 0 votes

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


title: Find the weight of five apples

text:
# Question
Title: Find the weight of five apples
## Problem

John bought 5 apples. You are given the weights of every group of four apples, and must then find the weights of the apples themselves.

For example, if all apples without the first one weigh 798 g, without the second - 794 g, without the third - 813 g, without the fourth - 806 g, and without the fifth - 789 g, the weights are 202, 206, 187, 194, and 211.

## Rules

1. The solution of the problem by enumeration is allowed
2. Consider the number of points as follows: the number of bytes in your code. The lower the number of points, the better.

Have fun!

# Answer
# MathGolf, 3 (or 5) bytes

```
Σ¼,

```

No idea why MathGolf has a single-byte `a//4` builtin, but it's pretty useful here. ;)

Try it online.

With strict input of space-delimited values it would be 5 bytes instead:

```
ê_Σ¼,

```

Try it online.

**Explanation:**

```
     # Optional for stricter space-delimited input:
ê    # Push the inputs as integer-array
 _   # Duplicate it

Σ    # Sum the values together
 ¼   # Integer-divide it by 4
  ,  # Subtract each value in the list from this sum//4
     # (after which the entire stack is output implicitly)

```
> 6 votes

# Answer
# Vyxal, ~~9~~ ~~7~~ ~~6~~ 5 bytes

```
∑4ḭ$-

```

Try it Online!

## Explanation

```
∑4ḭ$-
          # (implicit input)
∑         # Sum
 4ḭ       # Divide the sum by four
   $-     # Swap and subtract

```

*-2 bytes thanks to a stone arachnid*

*-1 byte thanks to ovs*
> 5 votes

# Answer
# BQN, ~~8~~ 6 bytes

*Edit: -2 bytes thanks to ovs*

```
-+´÷⟜4

```

Try it at BQN online REPL

```
    ÷⟜4     # divide each of the input values by 4
 +´         # and then fold the 'plus' function across them
-           # using the negative of the input as a list of starting values
            # (so effectively we start the fold using each negative input value
            # in parallel as a starting value)

```
> 4 votes

# Answer
# Python, 32 bytes

```
lambda a:[sum(a)/4-x for x in a]
```

Attempt This Online!
> 3 votes

# Answer
# Haskell, 18 bytes

```
map=<<(-).(/4).sum
```

Attempt This Online!
> 3 votes

# Answer
# Japt v2.0a0 `-m`, 5 bytes

```
aWx÷4

```

Try it
> 3 votes

# Answer
# λ-2d, 456 squares

the program can be imported in the playground with the following JSON file

```
{"41,13":"entry","41,18":"entry","41,23":"entry","41,28":"entry","41,32":"entry","42,13":"end_s","42,18":"end_s","42,23":"end_s","42,28":"end_s","42,32":"end_s","43,13":"end_e","43,18":"end_e","43,23":"end_e","43,28":"end_e","43,32":"end_e","39,15":"wire_nw","39,20":"wire_nw","39,25":"wire_nw","39,30":"wire_nw","39,34":"wire_nw","38,15":"wire_ne","38,20":"wire_ne","38,25":"wire_ne","38,30":"wire_ne","38,34":"wire_ne","44,13":"frame_tl","44,18":"frame_tl","44,23":"frame_tl","44,28":"frame_tl","44,32":"frame_tl","45,13":"wire_we","45,18":"wire_we","45,23":"wire_we","45,28":"wire_we","45,32":"wire_we","46,13":"wire_we","46,18":"wire_we","46,23":"wire_we","46,28":"wire_we","46,32":"wire_we","47,13":"wire_we","47,18":"wire_we","47,23":"wire_we","47,28":"wire_we","47,32":"wire_we","47,15":"wire_we","47,20":"wire_we","47,25":"wire_we","47,30":"wire_we","47,34":"wire_we","46,15":"wire_we","46,20":"wire_we","46,25":"wire_we","46,30":"wire_we","46,34":"wire_we","45,15":"wire_we","45,20":"wire_we","45,25":"wire_we","45,30":"wire_we","45,34":"wire_we","48,13":"wire_sw","48,18":"wire_sw","48,23":"wire_sw","48,28":"wire_sw","48,32":"wire_sw","48,15":"wire_nw","48,20":"wire_nw","48,25":"wire_nw","48,30":"wire_nw","48,34":"wire_nw","44,15":"wire_ne","44,20":"wire_ne","44,25":"wire_ne","44,30":"wire_ne","44,34":"wire_ne","44,14":"wire_ns","44,19":"wire_ns","44,24":"wire_ns","44,29":"wire_ns","44,33":"wire_ns","48,14":"wire_ns","48,19":"wire_ns","48,24":"wire_ns","48,29":"wire_ns","48,33":"wire_ns","42,14":"wire_nw","42,19":"wire_nw","42,24":"wire_nw","42,29":"wire_nw","42,33":"wire_nw","41,14":"wire_we","41,19":"wire_we","41,24":"wire_we","41,29":"wire_we","41,33":"wire_we","40,14":"wire_we","40,19":"wire_we","40,24":"wire_we","40,29":"wire_we","40,33":"wire_we","38,14":"wire_sw","38,19":"wire_sw","38,24":"wire_sw","38,29":"wire_sw","38,33":"wire_sw","39,14":"func_call","39,19":"func_call","39,24":"func_call","39,29":"func_call","39,33":"func_call","39,13":"joint_nsw","39,18":"joint_nsw","39,23":"joint_nsw","39,28":"joint_nsw","38,13":"wire_we","38,18":"wire_we","38,23":"wire_we","38,28":"wire_we","37,13":"wire_se","37,18":"wire_se","37,23":"wire_se","37,28":"wire_se","37,14":"wire_nswe","37,19":"wire_nswe","37,24":"wire_nswe","37,29":"wire_nswe","37,17":"wire_nw","37,22":"wire_nw","37,27":"wire_nw","37,32":"wire_nw","36,17":"wire_se","36,22":"wire_se","36,27":"wire_se","36,32":"wire_se","37,15":"wire_ns","37,20":"wire_ns","37,25":"wire_ns","37,30":"wire_ns","36,15":"wire_nw","36,20":"wire_nw","36,25":"wire_nw","36,30":"wire_nw","36,34":"wire_nw","35,15":"wire_ne","35,20":"wire_ne","35,25":"wire_ne","35,30":"wire_ne","35,34":"wire_ne","35,14":"wire_sw","35,19":"wire_sw","35,24":"wire_sw","35,29":"wire_sw","35,33":"wire_sw","36,14":"func_call","36,19":"func_call","36,24":"func_call","36,29":"func_call","36,33":"func_call","36,13":"joint_nsw","36,18":"joint_nsw","36,23":"joint_nsw","36,28":"joint_nsw","35,13":"wire_we","35,18":"wire_we","35,23":"wire_we","35,28":"wire_we","34,13":"wire_se","34,18":"wire_se","34,23":"wire_se","34,28":"wire_se","34,14":"wire_nswe","34,19":"wire_nswe","34,24":"wire_nswe","34,29":"wire_nswe","34,17":"wire_nw","34,22":"wire_nw","34,27":"wire_nw","34,32":"wire_nw","33,17":"wire_se","33,22":"wire_se","33,27":"wire_se","33,32":"wire_se","34,15":"wire_ns","34,20":"wire_ns","34,25":"wire_ns","34,30":"wire_ns","33,15":"wire_nw","33,20":"wire_nw","33,25":"wire_nw","33,30":"wire_nw","33,34":"wire_nw","32,15":"wire_ne","32,20":"wire_ne","32,25":"wire_ne","32,30":"wire_ne","32,34":"wire_ne","32,14":"wire_sw","32,19":"wire_sw","32,24":"wire_sw","32,29":"wire_sw","32,33":"wire_sw","33,14":"func_call","33,19":"func_call","33,24":"func_call","33,29":"func_call","33,33":"func_call","33,13":"joint_nsw","33,18":"joint_nsw","33,23":"joint_nsw","33,28":"joint_nsw","32,13":"wire_we","32,18":"wire_we","32,23":"wire_we","32,28":"wire_we","31,13":"wire_se","31,18":"wire_se","31,23":"wire_se","31,28":"wire_se","31,14":"wire_nswe","31,19":"wire_nswe","31,24":"wire_nswe","31,29":"wire_nswe","31,17":"wire_nw","31,22":"wire_nw","31,27":"wire_nw","31,32":"wire_nw","30,17":"wire_se","30,22":"wire_se","30,27":"wire_se","30,32":"wire_se","31,15":"wire_ns","31,20":"wire_ns","31,25":"wire_ns","31,30":"wire_ns","30,15":"wire_nw","30,20":"wire_nw","30,25":"wire_nw","30,30":"wire_nw","30,34":"wire_nw","29,15":"wire_ne","29,20":"wire_ne","29,25":"wire_ne","29,30":"wire_ne","29,34":"wire_ne","29,14":"wire_sw","29,19":"wire_sw","29,24":"wire_sw","29,29":"wire_sw","29,33":"wire_sw","30,14":"func_call","30,19":"func_call","30,24":"func_call","30,29":"func_call","30,33":"func_call","30,13":"joint_nsw","30,18":"joint_nsw","30,23":"joint_nsw","30,28":"joint_nsw","29,13":"wire_we","29,18":"wire_we","29,23":"wire_we","29,28":"wire_we","28,13":"wire_se","28,18":"wire_se","28,23":"wire_se","28,28":"wire_se","28,14":"wire_nswe","28,19":"wire_nswe","28,24":"wire_nswe","28,29":"wire_nswe","28,17":"wire_nw","28,22":"wire_nw","28,27":"wire_nw","28,32":"wire_nw","27,17":"wire_se","27,22":"wire_se","27,27":"wire_se","27,32":"wire_se","28,15":"wire_ns","28,20":"wire_ns","28,25":"wire_ns","28,30":"wire_ns","27,14":"func_call","27,19":"func_call","27,24":"func_call","27,29":"func_call","27,33":"func_call","27,13":"joint_nsw","27,18":"joint_nsw","27,23":"joint_nsw","27,28":"joint_nsw","26,13":"wire_se","26,18":"wire_se","26,23":"wire_se","26,28":"wire_se","26,14":"wire_ns","26,19":"wire_ns","26,24":"wire_ns","26,29":"wire_ns","26,15":"wire_ns","26,20":"wire_ns","26,25":"wire_ns","26,30":"wire_ns","26,16":"wire_ne","26,21":"wire_ne","26,26":"wire_ne","26,31":"wire_ne","27,16":"wire_we","27,21":"wire_we","27,26":"wire_we","27,31":"wire_we","29,16":"wire_we","29,21":"wire_we","29,26":"wire_we","29,31":"wire_we","30,16":"wire_we","30,21":"wire_we","30,26":"wire_we","30,31":"wire_we","32,16":"wire_we","32,21":"wire_we","32,26":"wire_we","32,31":"wire_we","33,16":"wire_we","33,21":"wire_we","33,26":"wire_we","33,31":"wire_we","35,16":"wire_we","35,21":"wire_we","35,26":"wire_we","35,31":"wire_we","36,16":"wire_we","36,21":"wire_we","36,26":"wire_we","36,31":"wire_we","39,16":"wire_sw","39,21":"wire_sw","39,26":"wire_sw","39,31":"wire_sw","39,17":"wire_ns","39,22":"wire_ns","39,27":"wire_ns","39,32":"wire_ns","38,16":"wire_we","38,21":"wire_we","38,26":"wire_we","38,31":"wire_we","28,16":"wire_nswe","28,21":"wire_nswe","28,26":"wire_nswe","28,31":"wire_nswe","31,16":"wire_nswe","31,21":"wire_nswe","31,26":"wire_nswe","31,31":"wire_nswe","34,16":"wire_nswe","34,21":"wire_nswe","34,26":"wire_nswe","34,31":"wire_nswe","37,16":"wire_nswe","37,21":"wire_nswe","37,26":"wire_nswe","37,31":"wire_nswe","28,33":"wire_we","31,33":"wire_we","34,33":"wire_we","37,33":"wire_we","39,12":"num_7","40,12":"num_8","41,12":"num_9","36,11":"num_8","37,11":"num_0","38,11":"num_6","33,12":"num_8","34,12":"num_1","35,12":"num_3","30,11":"num_7","31,11":"num_9","32,11":"num_4","28,12":"num_9","29,12":"num_8","27,12":"num_7","30,12":"wire_ns","36,12":"wire_ns","27,15":[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],"27,20":[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],"27,25":[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],"27,30":[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],"27,34":[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],"53,12":"func_def","55,12":"func_def","57,12":"func_def","59,12":"func_def","61,12":"func_def","54,12":"end_s","58,12":"end_s","56,12":"end_s","60,12":"end_s","62,12":"end_s","63,12":"end_e","54,11":"label","55,11":[0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0],"53,11":"wire_se","54,13":"joint_nse","55,16":"op_plus","57,16":"op_plus","59,16":"op_plus","61,16":"op_plus","55,15":"func_call","57,15":"func_call","59,15":"func_call","61,15":"func_call","56,13":"wire_nswe","58,13":"wire_nswe","61,13":"wire_we","60,13":"wire_nswe","62,13":"wire_nswe","59,13":"wire_we","57,13":"wire_we","55,13":"wire_we","55,14":"wire_sw","54,14":"wire_ne","56,15":"wire_nw","58,15":"wire_nw","60,15":"wire_nw","57,14":"wire_sw","59,14":"wire_sw","60,14":"func_call","61,14":"wire_sw","56,14":"func_call","58,14":"func_call","62,14":"func_call","62,15":"wire_nw","63,14":"wire_sw","63,15":"wire_ns","63,16":"func_call","63,17":"op_div","64,16":"wire_nw","64,15":"func_call","64,14":"num_4","65,15":"wire_sw","65,16":"func_call","65,17":"op_minus","66,16":"wire_nw","66,14":"func_call","67,14":"wire_nw","66,13":"wire_sw","67,12":"wire_sw","66,15":"wire_ns","67,13":"wire_ns","63,13":"wire_we","64,13":"wire_we","65,13":"wire_we","64,12":"wire_we","65,12":"wire_we","66,12":"wire_we"}

```

the function in itself is the right structure, the left one being 5 calls to the function with the 5 arguments in differents orders

---

## js equivalent

```
a=798
b=794
c=813
d=806
e=789
f=v=>w>=>x=>y=>z=>((v+w+x+y+z)/4)-v

f(a)(b)(c)(d)(e)
f(b)(c)(d)(e)(a)
f(c)(d)(e)(a)(b)
f(d)(e)(a)(b)(c)
f(e)(a)(b)(c)(d)

```

---

Language explanation can be found in the playground by loading the *cheatsheet* example, or in the release blog post
> 3 votes

# Answer
# Excel, 15 bytes

```
=SUM(A1#)/4-A1#

```

Input is in cell A1 as an array. For instance, `={798;794;813;806;789}`

---

# Excel, 19 bytes

```
=SUM(A1:A5)/4-A1:A5

```

Input is in the cells `A1:A5`. Doesn't rely on array input. Output is wherever the formula is. It's not a very interesting solution.
> 3 votes

# Answer
# TI-Basic, 7 bytes

```
sum(Ans)/4-Ans

```

Takes input in `Ans`. Output is stored in `Ans` and displayed.
> 2 votes

# Answer
# Desmos, 16 bytes

```
f(l)=l.total/4-l

```

Try It On Desmos!

Try It On Desmos! - Prettified
> 2 votes

# Answer
# LOLCODE, 216 bytes

```
HOW IZ I f YR a
I HAS A s ITZ 0
IM IN YR l UPPIN YR i TIL BOTH SAEM i 5
s R SUM OF s a'Z SRS i
IM OUTTA YR l
IM IN YR l UPPIN YR i TIL BOTH SAEM i 5
VISIBLE DIFF OF QUOSHUNT OF s 4 a'Z SRS i
IM OUTTA YR l
IF U SAY SO

```

Try it online!
> 2 votes

# Answer
# Pip, ~~9~~ 7 bytes

```
$+a/4-a
```

Attempt This Online!

*-2 bytes thanks to DLosc*
> 2 votes

# Answer
# Jelly, 4? 8 bytes

With a strict interpretation of Rule 1 (can't take as a program argument due to the "single line" part) - a full program that reads from STDIN and writes to STDOUT:

```
ɠḲVµS÷4_

```

Try it online!

...or with site default IO instead - a monadic Link that accepts a list of five numbers and yields a list of five numbers:

```
S÷4_

```

**Try it online!**

### How?

```
ɠḲVµS÷4_ - Main Link: no arguments
ɠ        - read a line from STDIN
 Ḳ       - split that at spaces
  V      - evaluate that as Jelly code -> list of the five four-apple-weights, W
   µ     - start a new monadic chain - f(W)
    S    - sum W
      4  - four
     ÷   - divide -> sum(W)/4
       _ - subtract W (vectorises) -> [sum(W)/4-w1, sum(W)/4-w2, sum(W)/4-w3, sum(W)/4-w4, sum(W)/4-w5]
         - implicit print

```
> 1 votes

# Answer
# Factor \+ `math.unicode`, 23 bytes

```
[ dup Σ 4 / swap n-v ]

```

Try it online!

## Explanation

```
       ! { 798 794 803 816 789 }
dup    ! { 798 794 803 816 789 } { 798 794 803 816 789 }
Σ      ! { 798 794 803 816 789 } 4000
4      ! { 798 794 803 816 789 } 4000 4
/      ! { 798 794 803 816 789 } 1000
swap   ! 1000 { 798 794 803 816 789 }
n-v    ! { 202 206 197 184 211 }

```
> 1 votes

# Answer
# Ruby, 22 bytes

```
->a{a.map{a.sum/4-_1}}
```

Attempt This Online!
> 1 votes

# Answer
# 05AB1E, ~~9~~ 4 bytes

```
O4÷α

```

Try it online!

*-5 bytes thanks to Kevin Cruijssen*
> 1 votes

# Answer
# Julia 1.0, 14 bytes

```
!l=sum(l/4).-l

```

Try it online!
> 1 votes

# Answer
# , 14 bytes

```
\(x)sum(x)/4-x

```

Try it online!

Uses the new lambda, `\`, introduced in R 4.1.
> 1 votes

# Answer
# jq, ~~20~~ 9 bytes

```
add/4-.[]
```

Attempt This Online!

*-11 bytes thanks to @ovs*
> 1 votes

# Answer
# , 7 bytes

```
-~4%~+/
```

Attempt This Online!
> 1 votes

# Answer
# Burlesque, 9 bytes

```
J++4./j?-

```

Try it online!

```
J   # Duplicate
++  # Sum
4./ # Divide by 4
j   # Swap
?-  # Subtract from each

```
> 1 votes

# Answer
# Halfwit, 5 bytes

```
kJ>+<k+N+N

```

Try it online.

Inputs as a list of BigInts.

**Explanation:**

```
kJ          # Sum the (implicit) input-list
  >+<       # Push compressed BigInt 4n
     k+     # Integer-divide the sum by this 4
       N+N  # Subtract the values in the (implicit) input-list from this value:
       N    #  Negate the value
        +   #  Add it to each value in the (implicit) input-list
         N  #  Negate each value in the list
            # (after which the result is output implicitly)

```
> 1 votes

# Answer
# C (gcc), ~~61~~ 58 bytes

```
n,i;f(int*a){for(i=10;i--;)i>4?n+=a[i%5]:(a[i]=n/4-a[i]);}

```

Try it online!

*-3 bytes thanks to ceilingcat*
> 1 votes

# Answer
# x86 32-bit machine code, 32 bytes

```
00000000: 87ca 31c0 6a05 5903 448a fce2 fac1 e802  ..1.j.Y.D.......
00000010: 6a05 5950 2b44 8afc 8944 8afc 58e2 f4c3  j.YP+D...D..X...

```

## Assembly

```
section .text
	global func
func:					;void func(int *ecx);
	; int *edx=ecx; int eax=0;
	xchg ecx, edx
	xor eax,eax

	; for(ecx=5;ecx>0;ecx--)eax+=edx[ecx-1]
	push 0x5
	pop ecx
	add:
	add eax, [edx + 4*ecx-4]
	loop add

	; eax = eax / 4
	shr eax, 2

	; for(ecx=5;ecx>0;ecx--)edx[ecx-1]=eax-edx[ecx-1];
	push 0x5
	pop ecx
	sub:
	push eax
	sub eax, [edx + 4*ecx-4]
	mov [edx + 4*ecx-4], eax
	pop eax
	loop sub

	; return
	ret

```

Takes a pointer to an array of 5 integers in ECX (fastcall convention), and modifies the array in place with the results.

Try it online!
> 1 votes

# Answer
# Nibbles, 4 bytes (8 nibbles)

```
+/+$4*~

```

```
  +         # sum of
   $        # the input
 /          # divided by
    4       # 4
+           # added to
            # (implicitly) each element of input
     *      # multiplied by
      ~     # -1

```
> 1 votes

# Answer
# , 7 bytes

```
-~4%~+/

```

Nothing new here.

Attempt This Online!

```
-~4%~+/
     +/  NB. sum
  4%~    NB. divide result by 4
-~       NB. subtract result by input, vectorized

```
> 1 votes

# Answer
# APL+WIN, ~~13~~ 11 bytes

-2 bytes thanks to att

Prompts for an vector of total weight minus each apple in turn

```
(+/w÷4)-w←⎕

```

Try it online! Thanks to Dyalog APL Classic
> 0 votes

# Answer
# Charcoal, 7 bytes

```
Ｉ⁻÷Σθ⁴θ

```

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

```
    θ   Input list
   Σ    Take the sum
  ÷     Integer divided by
     ⁴  Literal integer `4`
 ⁻      Vectorised subtract
      θ Input list
Ｉ       Cast to string
        Implicitly print

```

9 bytes for a version that works with two or more apples, not just five:

```
Ｉ⁻÷Σθ⊖Ｌθθ

```

Try it online! Link is to verbose version of code.
> 0 votes

# Answer
# JavaScript (Node.js), ~~34~~ 32 bytes

```
a=>a.map(e=>eval(a.join`+`)/4-e)
```

Attempt This Online!

<sup>-2 bytes thanks to Steffan</sup>
> 0 votes

# Answer
# Red, 28 bytes

```
func[v][v -((sum v)/ 4)* -1]

```

Try it online!
> 0 votes

# Answer
# C (clang), 60 bytes

```
b,c;f(*a){for(b=c=0;b<5;c+=a[b++]);for(;b--;a[b]=c/4-a[b]);}

```

Try it online! Takes an array of 5 integers and modifies the array in-place.
> 0 votes

# Answer
# PARI/GP, 23 bytes

```
a->[vecsum(a)/4-t|t<-a]
```

Attempt This Online!
> 0 votes

# Answer
# Wolfram Language (Mathematica), 9 bytes

```
Tr@#/4-#&

```

Try it online!
> 0 votes

# Answer
# MATLAB/Octave, 14 bytes

```
@(x)sum(x)/4-x

```

Try it online!
Basically the same algorithm everyone else uses, as lambda function.
> 0 votes

# Answer
# Java (JDK), 57 bytes

```
a->a.stream().map(x->a.stream().mapToInt(i->i).sum()/4-x)

```

Try it online!
> 0 votes

# Answer
# Ruby, 46 bytes

```
i=gets.split.map(&:to_i);i.map{|n|p i.sum/4-n}
```

Attempt This Online!
> 0 votes

# Answer
# Scala, 49 bytes

saved many bytes, but it run so slow.

Try it online!

```
val f:List[Int]=>List[Int]=a=>a.map(x=>a.sum/4-x)

```
> 0 votes

# Answer
# Thunno 2, 4 bytes

```
S4÷_

```

Try it online!

#### Explanation

```
S4÷_  # Implicit input
S     # Sum the list
 4÷   # Floor divide by 4
   _  # Subtract input from this
      # Implicit output

```
> 0 votes

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


title: Enthusiastically Russianify a String

text:
# Question
Title: Enthusiastically Russianify a String
Many of you may have interacted with people from Russia on the internet at some point, and a subset of you may have noticed the slightly odd method they have of expressing themselves.

e.g. `удали игру нуб)))`

where the `)))` are added for emphasis on the previous statement, I have been working on a theory that the ratio of `)`'s to the rest of the string is directly proportional to the amount of implied emphasis, however I oftentimes find it difficult to compute the ratio on the fly, as I am also trying to cope with a slew of abuse, so I would like the shortest possible code to help me calculate what the resulting string should be, for a value of enthusiasm between 0 and 500%, given the original, unenthusiastic string, this will aid my research greatly as I will not have to type out bulky scripts every time I wish to test my hypothesis.

So, the challenge:

write a full program or function, which, provided two arguments, a string of unknown length, and a number, in either integer format (between 0 and 500) or in decimal format (between 0 and 5, with 2 points of accuracy) will

* return/display the original string, suffixed with a number of `)`'s
* the number will be the calculated as a ratio of the input number to the string length.
* so if the number 200, or 2.00 was provided, 200% of the string must be suffixed as `)`'s
* the number of brackets rounded to in decimal situations does not matter.
* script is required to support Printable ASCII characters.
* only has to support one input number format, of your choice.

Examples:

```
"codegolf" 125      = codegolf))))))))))
"codegolf" 75       = codegolf))))))
"noob team omg" 0.5 = noob team omg))))))
"hi!" 4.99          = hi!)))))))))))))))

```

Example code (PowerShell) (with decimal input):

```
Function Get-RussianString ([string]$InputStr,[decimal]$Ratio){
    $StrLen = $InputStr.Length
    $SuffixCount = $StrLen * $Ratio
    $Suffix = [string]::New(")",$SuffixCount)
    return $InputStr + $Suffix
}

Get-RussianString "codegolf" 0.5
codegolf))))

```

This is so shortest code wins!

# Answer
> 16 votes
# Jelly, 7 bytes

```
ȮL×Ċ”)x

```

**Try it online!**

Uses the decimal format.

### How?

```
ȮL×Ċ”)x - Main link: string, decimal
Ȯ       - print string
 L      - length(string)
  ×     - multiply by the decimal
   Ċ    - ceiling (since rounding method is flexible)
    ”)  - a ')' character
      x - repeated that many times
        - implicit print

```

# Answer
> 17 votes
# Perl 6, 21 bytes

```
{$^a~")"x$^b*$a.comb}

```

# Answer
> 16 votes
## Common Lisp, ~~59~~ ~~52~~ 50

Parentheses? I am in.

```
(lambda(s n)(format()"~a~v@{)~}"s(*(length s)n)0))

```

### Details

```
(lambda(s n)               ; two arguments (string and ratio)
  (format ()               ; format as string
          "~a~v@{)~}"      ; control string (see below)
          s                ; first argument (string)
          (* (length s) n) ; second argument (number of parens)
          0))              ; one more element, the value does not matter

```

### Format control string

* `~a` : pretty print argument (here the given string)
* `~v@{...~}` : iteration block, limited to V iteration, where V is taken as an argument, namely the `(* ...)` expression. The iteration is supposed to iterate over a list, but when you add the `@` modifier, the list is the remaining list of arguments to the format function. There must be at least one element in the iterated list (otherwise we exit, disregarding V). That is why there is an additional argument to format (0).

Since no element in the list is consumed by the format, the loop is infinite but fortunately, it is also bounded by V, a.k.a. the number of parentheses to be printed.

---

Edit: thanks to Michael Vehrs for pointing out that there is no need to round the numerical argument (the question allows to truncate/round however we want, so the default behavior works here).

# Answer
> 9 votes
# JavaScript ES6, 38 31 30 bytes

```
s=>n=>s+')'.repeat(s.length*n)

```

```
f=s=>n=>s+')'.repeat(s.length*n)

console.log(f("hi!")(4.99))
```

# Answer
> 8 votes
# Python 2, 29 bytes

```
lambda s,p:s+len(s)*p/100*')'

```

**s** in the string, **p** is the percentage (integer).

Try it online!

# Answer
> 7 votes
# 05AB1E, ~~9~~ 8 bytes

```
g*ï')×¹ì

```

Try it online!

```
g*       # Length, multiplied by emphasis.
  ï')×   # Covnerted to an integer, push that many parenthesis.
      ¹ì # Prepend original string.

```

Works for both integer and decimal, arguments order: `f(String, Double)`

# Answer
> 7 votes
# Python, 30 bytes

```
lambda s,r:s+')'*int(len(s)*r)

```

Uses the decimal input.

Try it online!

# Answer
> 7 votes
# Pyth, 8 bytes

```
*\)s*lpz

```

Online Test! Takes the excitement ratio first, then the string to be enthused about.

Explanation:

```
      pz  print out the enthused string
     l    ... and get its length
    *...Q multiply that by the ratio
   s      floor to get an integer, let's call this S
 \)       single-character string ")"
* ")" S   multiply that integer by the string, which gives a string of )s of length S.
          implicitly print that string of S )s.

```

# Answer
> 6 votes
# PowerShell, 33 bytes

```
$a,$b=$args;$a+')'*($b*$a.Length)

```

Try it online!

Supports decimal format.

# Answer
> 5 votes
# R, ~~62~~ ~~46~~ 42 bytes

Anonymous function that takes string `a` and decimal `n`, prints output to stdout.

```
pryr::f(cat(a,rep(")",n*nchar(a)),sep=""))

```

# Answer
> 4 votes
# Pyth, 9 bytes

```
*s*lpzE")

```

Takes two lines of input: string and ratio (decimal).

Try it on pyth.herokuapp.com

### Explanation

`A` denotes a function's first argument, `B` its second argument.

```
*s*lpzE")
    pz     # print the input string
   lAA     # take the length of the printed string
      E    # read the next line of input (the emphasis ratio)
  *AAAB    # multiply the length by the ratio
 sAAAAA    # floor the result
*AAAAAA")  # repeat ")" n times
           # implicit print

```

# Answer
> 4 votes
# TI-Basic, 33 bytes

Takes decimal input.

```
Prompt Str1,A
")
For(I,0,9
Ans+Ans
End
Str1+sub(Ans,1,AI

```

# Answer
> 4 votes
# Perl 5, 29 bytes

```
sub{($_=pop).')'x(y///c*pop)}

```

(Number is first arg, string is second.)

Try it online!

# Answer
> 3 votes
## CJam, 9 bytes

```
l_,ld*')*

```

Try it online!

Input string on the first line, emphasis ratio in range 0 to 5 on the second.

### Explanation

```
l    e# Read input string.
_,   e# Duplicate, get length.
ld   e# Read emphasis ratio.
*    e# Multiply by length.
')*  e# Get that many parentheses.

```

# Answer
> 3 votes
# MATL, ~~11~~ ~~10~~ 8 bytes

```
yn*:"41h

```

This solution uses the decimal form of the second input

**Try it online!**

**Explanation**

```
        % Implicitly grab first input as a string
        % Implicitly grab the second input as a number
y       % Make a copy of the first input
n       % Compute the length of the string
*       % Multiply the decimal by the length to determine the # of )'s (N)
:       % Create the array [1...N]
"       % For each element in this array
  41    % Push 41 to the stack (ACSII for ")")
  h     % Horizontally concatenate this with the current string
        % Implicit end of for loop and display

```

# Answer
> 3 votes
# sB~, 17 bytes

```
i\,N?\;')'*(N*l(\

```

Explained:

```
i\,N    input a string and a number
?\;     print the string
')'*    also print ) multiplied by...
(N*l(\  the number times the string length.

```

Parentheses are closed automatically

Here's the output of the compiler, if you're interested:

```
 INPUT  S$ ,N? S$ ;")"*(N* LEN(  S$ ))

```

This version of the compiler was written on 1/27/2017 at 11:12 pm, which might have been a few minutes after this question was posted. So here's a version which works on the oldest version of the compiler, written an hour earlier: `iS$,N?S$;')'*(N*l(S$))` (22 bytes)

# Answer
> 3 votes
# PostgreSQL, 102 bytes

```
create function q(text,int)returns text as $$select rpad($1,(100+$2)*length($1)/100,')')$$language sql

```

### Details

Uses the integer input format.

This simply right-pads the input string with parens out to the target length.

```
create function q(text,int)
returns text as $$
    select rpad($1,             -- Pad the string input
        (100 + $2) *            -- to 100 + int input % ...
        length($1) / 100,       -- ...of the input string
        ')')                    -- with ) characters
$$ language sql

```

Called with

```
select q('codegolf', 125), q('codegolf', 75);
select q('noob team omg', 50), q('hi!', 499);

```

# Answer
> 2 votes
## C# Interactive, ~~77~~ 67 bytes

```
string r(string s,int p)=>s+new string(')',(int)(s.Length*p/100d));

```

C# interactive is sweet.

# Answer
> 2 votes
# Bash \+ coreutils, 45 bytes

```
echo $1`seq -s\) $[${#1}*$2/100+1]|tr -cd \)`

```

Try it online!

Integer input.

# Answer
> 2 votes
# Groovy, 27 bytes

Straightforward solution

```
{s,r->s+')'*(s.length()*r)}

```

Test program :

```
def f = {s,r->s+')'*(s.length()*r)}

println f("hi!", 4.99)
println f("noob team omg", 0.5)

```

# Answer
> 2 votes
# Rebol, 39 bytes

```
func[a b][append/dup a")"b * length? a]

```

# Answer
> 2 votes
# Clojure, 40 bytes

Quite boring solution :

```
#(reduce str %(repeat(*(count %)%2)")"))

```

Just reduces `str` function on a list of closing parentheses with a string as initial parameter.

See it online : https://ideone.com/5jEgWS

Not-so-boring solution (64 bytes) :

```
#(.replace(str(nth(iterate list(symbol %))(*(count %)%2)))"(""")

```

Converts input string to a symbol (to get rid of quotes) and repeatedly applies function `list` on it generating infinite sequence like this: `(a (a) ((a)) (((a))) ... )`. Takes `nth` element converts it to string and replaces all opening parentheses with nothing.

See it online : https://ideone.com/C8JmaU

# Answer
> 2 votes
# SimpleTemplate, 92 bytes

Takes the string as the first parameter and the "ratio" as the second.
The ratio is between 0 and 5, with 2 decimal places.

```
{@echoargv.0}{@callstrlen intoL argv.0}{@set*Y argv.1,L}{@callstr_repeat intoO")",Y}{@echoO}

```

As you can see, it is non-optimal.
The 2 `{echo}` there could be reduced to 1.
Due to a bug in the compiler, this code can't be reduced much further.

---

**Ungolfed:**

```
{@echo argv.0}
{@call strlen into length argv.0}
{@set* ratio argv.1, length}
{@call str_repeat into parenthesis ")", ratio}
{@echo parenthesis}

```

---

If no bug existed, the code would look like this, 86 bytes:

```
{@callstrlen intoL argv.0}{@set*Y argv.1,L}{@callstr_repeat intoO")",Y}{@echoargv.0,O}

```

# Answer
> 2 votes
# International Phonetic Esoteric Language, 24 bytes

A reimplementation of the old answer into the new specification. Input is as a positive integer first, then the string.

```
ɪ{100}viħɖf0ɑ")"x1esøɒʕo

```

Explanation:

```
ɪ{100}viħɖf0ɑ")"x1esøɒʕo
ɪ                        (push input int)
 {100}                   (push 100)
      v                  (divide int//100)
       iħ                (push input str, push len)
         ɖ               (rotate top 3 clockwise)
          f              (multiply int//100 * len)
           0             (push 0)
            ɑ            (begin loop, from 0 to int//100 * len)
             ")"         (push ")")
                x        (concat)
                 1esø    (increment index)
                     ɒ   (end loop)
                      ʕ  (list to str)
                       o (print)

```

---

# International Phonetic Esoteric Language, 18 bytes (WIP language) (OLD)

I discovered some bugs in my interpreter because of this challenge. Takes input as `string` then `integer`.

```
iɢ291tʃɪðθœ<)>ɲqɶo

```

No TIO interpreter yet, but is runnable by cloning the repository above, and calling `python3 main.py "code here"`.

```
iɢ291tʃɪðθœ<)>ɲqɶo
i                  ; push string input
 ɢ                 ; peek, push string length
  291tʃ            ; push (1 + 9)^2
       ɪ           ; push number input
        ðθ         ; push [num / 100 * len]
          œ        ; start loop: pop, run ceil(n) times
           <)>     ; push string ")"
              ɲ    ; swap top 2 elements of the stack
               q   ; pop, pop, push concatenated strings
                ɶ  ; end loop
                 o ; output

```

Sample cases:

```
python3 main.py "iɢ291tʃɪðθœ<)>ɲqɶo"
codegolf
125
codegolf))))))))))

python3 main.py "iɢ291tʃɪðθœ<)>ɲqɶo"
iɢ291tʃɪðθœ<)>ɲqɶo
300
iɢ291tʃɪðθœ<)>ɲqɶo))))))))))))))))))))))))))))))))))))))))))))))))))))))

python3 main.py "iɢ291tʃɪðθœ<)>ɲqɶo"
less than 1.00
50
less than 1.00)))))))

```

# Answer
> 2 votes
# Stax, 7 bytes

```
é┴eó¡µf

```

Run and debug it

# Answer
> 1 votes
## SmileBASIC, 29 bytes

```
INPUT S$,N?S$;")"*(LEN(S$)*N)

```

# Answer
> 1 votes
# Gol\>\<\> (Golfish), 17 bytes

```
i:a=?v
R*Il~/Hr)`

```

Try it here.

The top line reads characters (`i`) until it finds a newline (ASCII 10, `a`), then goes down (`v`).

Then we discard one character (the newline) with `~`, push the length of the stack (`l`), read a float (`I`), multiply the two, and repeatedly (`R`) push the character ")" that many times. Finally, reverse the stack (`r`), output it and halt (`H`).

# Answer
> 1 votes
# PHP, 50 bytes

```
<?=str_pad($s=$argv[1],strlen($s)*++$argv[2],")");

```

takes string and decimal number as command line arguments; cuts padding. Run with `-r`;

**breakdown**

```
<?=                     // print ...
str_pad(                    // pad
    $s=$argv[1],            // string=argument 1
    strlen($s)*++$argv[2],  // to string length*(1+argument 2)
    ")"                     // using ")" as padding string
);

```

# Answer
> 1 votes
# Mathematica, 24 bytes

```
#<>Table[")",#2Tr[1^#]]&

```

Unnamed function taking a list of characters and a decimal number as input and returning a string. `Tr[1^#]` is a sneaky golfy way to calculate the length of a list, so `#2Tr[1^#]` computes the required number of parentheses. `Table[")",...]` produces a list of that many right parentheses (all decimals automatically rounded down, which is nice). Finally, `#<>` concatenates the input string to the parentheses, flattening the list produced by `Table` as it goes.

# Answer
> 1 votes
# Ruby, 25 bytes

```
->(s,n){s+')'*(s.size*n)}

```

I'm using **lambdas**. The test program would be something like:

```
f=->(s,n){s+')'*(s.size*n)}
f.("codegolf", 1.5)        # => "codegolf))))))))))))"
f.("hi!", 4.99)            # => "hi!))))))))))))))"

```

# Answer
> 1 votes
# GNU AWK, 59 bytes

```
{t=sprintf("%"n*length(s)"s","");gsub(/ /,")",t);print s t}

```

Accepts arguments on command line (using the decimal form) like so:

```
: | awk -v s="codegolf" -v n=0.75 -f russianify.awk

```

Yes, AWK requires *something* to be attached to stdin, even if that something is 0 bytes returned by the no-op shell builtin. You could also use `echo | awk ...`, or really *anything* that doesn't contain a newline.

# Answer
> 1 votes
# Clojure, 68 bytes

An anonymous function that accepts decimal input.

```
(fn [s n] (print (str s (reduce str (repeat (* n (count s)) ")")))))

```

Literally the first Lisp program I've ever written! I'm already having fun.

# Answer
> 1 votes
# C++14, 43 bytes

As unnamed lambda modifying its input, assuming `s` is similar to `std::string` (has `.append(int,char)` and assuming `p` to be of floating point type:

```
[](auto&s,auto p){s.append(s.size()*p,41);}

```

Usage:

```
#include<string>
#include<iostream>

auto f=
[](auto&s,auto p){s.append(s.size()*p,41);}
;

int main() {
 std::string s = "abcdefghijk";
 f(s,0.75);
 std::cout << s << std::endl;
}

```

# Answer
> 1 votes
# Haskell, 37 bytes

```
s!n=s++([1..div(n*length s)100]>>")")

```

Try it online! Usage: `"codegolf" ! 125`

---

A version that takes a decimal number: (41 bytes)

```
s!n=s++([1..n*toRational(length s)]>>")")

```

Try it online! Usage: `"codegolf" ! 1.25`

# Answer
> 1 votes
## Jellyfish, 16 bytes

```
P
,$')
 *i
 #
EI

```

Takes input as decimal, then newline, then string. Try it online!

## Explanation

Let's start from the bottom.

```
I

```

A raw string read from STDIN.

```
#
I

```

The length of the string.

```
*i
#
I

```

Multiply it by a number read from STDIN (the number is read first, since `i` comes before `I` in the source).

```
$')
*i
#
I

```

Repeat the character `)` that many times, rounding down.

```
,$')
 *i
 #
EI

```

Append to the original string (the `,` looks for arguments from the south and east, and `E` tells the southward seeker to turn east, where it finds the `I`).

```
P
,$')
 *i
 #
EI

```

Print the resulting string.

# Answer
> 1 votes
# Japt, 8 bytes

```
+')pUÊ*V

```

Try it

# Answer
> 1 votes
# Thunno 2, 6 bytes

```
l×')×+

```

Try it online!

Takes the string, then the decimal.

#### Explanation

```
l×')×+  '# Implicit input
l        # Length of string input
 ×       # Multiply by the number
  ')×   '# Multiply by ")"
         # (implicit floor)
     +   # Append to the input
         # Implicit output

```

---
Tags: code-golf, string
---


title: Sums of Consecutive Integers

text:
# Question
Title: Sums of Consecutive Integers
Before anyone says anything, similar and similar. But this is not a dupe.

---

Some positive integers can be written as the sum of at least two consecutive positive integers. For example, `9=2+3+4=4+5`. Write a function that takes a positive integer as its input and prints as its output the **longest** sequence of increasing consecutive positive integers that sum to it (any format is acceptable, though -5 bytes if the output is the increasing sequence separated by `+` as shown above. If there exists no such sequence, then the number itself should be printed.

This is code golf. Standard rules apply. Shortest code in bytes wins.

---

**Samples** (note that formatting varies)

```
Input:   9
Output:  2,3,4

Input:   8
Output:  8

Input:   25
Output:  [3,4,5,6,7]

```

# Answer
> 12 votes
## Python, 67 bytes

```
f=lambda n,R=[1]:n-sum(R)and f(n,[R+[R[-1]+1],R[1:]][sum(R)>n])or R

```

An oddly straightforward strategy: search for the interval R with the right sum.

* If the sum is too small, shift the right endpoint of the interval up one by appending the next highest number.
* If the sum is too large, shift up the left endpoint by removing the smallest element
* If the sum is correct, output R.

Since the bottom end of the interval only increases, longer intervals are found before shorter ones.

# Answer
> 7 votes
# Pyth, ~~12~~ 10 bytes

```
j\+hfqsTQ}M^SQ2

```

The code is **15 bytes** long and qualifies for the **-5 bytes** bonus. Try it online in the Pyth Compiler.

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

### How it works

```
j\+hfqsTQ}M^SQ2    (implicit) Store evaluated input in Q.

            S      Compute [1, ..., Q].
           ^  2    Get all pairs of elements of [1, ..., Q].
         }M        Reduce each pair by inclusive range. Maps [a, b] to [a, ..., b].
    f              Filter; for each pair T:
      sT             Add the integers in T.
     q  Q            Check if the sum equals Q.
                   Keep the pair if it does.
   h               Retrieve the first match.
                   Since the ranges [a, ..., b] are sorted by the value of a,
                   the first will be the longest, in ascending order.
j\+                Join, using '+' as separator.

```

# Answer
> 5 votes
# K (ngn/k), ~~40~~ 32 bytes

```
{^/!'1+i@'*>-/i:&x=s-\:s:+\!1+x}

```

Try it online!

*-8 bytes thanks to @ngn*

# Answer
> 3 votes
# Wolfram Language (Mathematica), ~~73~~ ~~68~~ ~~65~~ ~~56~~ ~~43~~ ~~42~~ 35 bytes

```
Range@#/.{___,x__,___}/;+x==#:>{x}&

```

Try it online!

# Answer
> 3 votes
# Haskell, ~~49~~ 48 bytes

```
f n=[[a..b]|a<-[1..n],b<-[a..n],sum[a..b]==n]!!0

```

# Answer
> 3 votes
# Jelly (fork), 5 bytes

```
ẆSƘ¹Ṫ

```

Try it online! (or rather, don't)

For an extra 3 bytes (again, doesn't work on TIO), we can get a score of 3

## How it works

```
ẆSƘ¹Ṫ - Main link. Takes N on the left
Ẇ     - Cast N to range and get all contiguous, non-empty sublists
  Ƙ¹  - Keep those for which the following is equal to N:
 S    -   Sum
    Ṫ - Take the last (and longest) one

```

# Answer
> 3 votes
# Vyxal, 11 - 5 = 6 bytes

```
ɾÞS≬∑?=c\+j

```

Just like most of the other answers in golfing languages.

Try it Online!

Explanation:

```
ɾ            # Range from 1 to n
 ÞS          # All sublists
   ≬         # Three element lambda
    ∑        #   Sum
      =      #   Equals
     ?       #   The input
       c     # First truthy item under function application
          j  # Join by:
        \+   # "+"

```

# Answer
> 3 votes
# Brachylog, 8 bytes

```
⟦₁s.+?!∧

```

Try it online!

### Explanation

```
⟦₁s.+?!∧
⟦₁         Inclusive range from 1 to the input number
  s        A consecutive sublist (trying longest sublists first)
   .       is the output
    +      Its sum
     ?     is the input
      !    Don't try any further possibilities
       ∧   Break unification with the output

```

# Answer
> 3 votes
# K (ngn/k), 61 41 bytes

```
h:{i{x':y}\:i:1+!x}
f:{i@*|&x=+/'i:,/h@x}

```

Try it online!

*¯20 bytes thanks to @doug*

# Answer
> 3 votes
# K (ngn/k), ~~27~~ 26 bytes

```
{*|(x=+/')#{y+!'x}.1+!2#x}

```

Try it online!

Uses doug's insight that to get a run you just need a pair of numbers.

# Answer
> 2 votes
# MATLAB, ~~87~~ 79 bytes

I know there is already a MATLAB answer, but this one is significantly different in approach.

```
x=input('');m=1:x;n=.5-m/2+x./m;l=max(find(~mod(n(n>0),1)));disp(m(1:l)+n(l)-1)

```

This also works on **Octave**. You can try online here. I've already added the code to `consecutiveSum.m` in the linked workspace, so just enter `consecutiveSum` at the command prompt, then enter the value (e.g. 25).

I am still working on reducing it down (perhaps adjusting the equation used a bit), but basically it finds the largest value `n` for which `m` is an integer, then displays the first `m` numbers starting with `n`.

So why does this work? Well basically there is a mathematical equation governing all those numbers. If you consider that they are all consecutive, and start from some point, you can basically say:

```
n+(n+1)+(n+2)+(n+3)+...+(n+p)=x

```

Now, from this it becomes apparent that the sequence is basically just the first `p` triangle numbers (including the 0'th), added to `p+1` lots of `n`. Now if we let `m=p+1`, we can say:

```
m*(n+(m-1)/2)==x

```

This is actually quite solvable. I am still looking for the shortest code way of doing it, I have some ideas to try and reduce the above code.

---

For an input of 25, the output would be:

```
3     4     5     6     7

```

# Answer
> 2 votes
# awk, 51 bytes

```
{while($0!=s+=s<$0?++j:-++i);while(++i-j)r=r i"+"}$0=r j

```

The code is 56 bytes, minus 5 bytes for the output format. I had to use 4 extra bytes to produce that format, so I actually saved 1 byte. Hooray! ;)

It's actually doing the hard work of summing up starting from 1 until the sum is bigger than the input. Then it begins substracting numbers starting from 1 until the number is smaller than the input. It keeps changing the start and end number this way until it found a result, which it then prints.

## Usage example

```
echo 303 | awk '{while($0!=s+=s<$0?++j:-++i);while(++i-j)r=r i"+"}$0=r j'

```

## Output of example

```
48+49+50+51+52+53

```

I've tried this for an input of `1e12` and it gave the correct result (`464562+...+1488562`) almost immediately. Though it took a while printing it of course...

# Answer
> 2 votes
# Jelly, 8 bytes

```
ẆS⁼¥Ðf⁸Ṫ

```

Try it online!

If I understand correctly, this could be an (11-5=6)-byte version:

```
ẆS⁼¥Ðf⁸Ṫj”+

```

# Answer
> 2 votes
# Prolog (SWI), ~~64 62~~ 51 bytes

*-2 bytes thanks to Steffan*

*-11 bytes thanks to Razetime's tip*

```
N+Z:-numlist(1,N,A),append([_,Z,_],A),sumlist(Z,N).

```

Try it online!

# Answer
> 2 votes
## Pyth, 12 - 5 = **7 bytes**

```
j\+efqQsT.:S

```

Test suite

The existing Pyth answer uses an older version of the language; new features have been added since.

##### Explanation:

```
j\+efqQsT.:S  | Full code
j\+efqQsT.:SQ | with implicit variables
--------------+----------------------------------------------------
           SQ | Get the range [1, ... input]
         .:   | Get all substrings, sorted by length
    f         | Filter for T such that
       sT     |  the sum of T
     qQ       |  equals the input
   e          | Get the last (longest) element of the filtered list
j\+           | Join by "+"

```

# Answer
> 1 votes
# Python 2, 94 bytes

```
n=input()
r=int((2*n)**.5)
while r:
 if~r%2*r/2==n%r:print range(n/r-~-r/2,n/r-~r/2);r=1
 r-=1

```

Input is taken from stdin. This solution is suitable for very large inputs.

This iterates over the possible solution lengths, *r*, having *r ≤ √(2n)*, and checks for a solution explicitly. In order for a solution to exist, if *r* is odd, *n mod r* must be zero, and if *r* is even, *n mod r* must be *r/2*.

---

**Sample Usage**

```
$ echo 8192 | python sum-con-int.py
[8192]

$ echo 1000002 | python sum-con-int.py
[83328, 83329, 83330, 83331, 83332, 83333, 83334, 83335, 83336, 83337, 83338, 83339]

$ echo 1000000006 | python sum-con-int.py
[250000000, 250000001, 250000002, 250000003]

```

I've deliberately choosen examples with relatively small outputs.

# Answer
> 1 votes
# Octave, 89 Bytes

This is the best I could do in Octave. The algorithm is the same as xnor's.

```
x=input('');k=i=1;while x;s=sum(k:i);if s<x;i++;elseif s>x;k++;else;x=0;end;end;disp(k:1)

```

In MATLAB this would be 95 bytes:

```
x=input('');k=1;i=1;while x;s=sum(k:i);if s<x;i=i+1;elseif s>x;k=k+1;else x=0;end;end;disp(k:i)

```

In MATLAB this runs in approx 0.1 seconds for input `2000000` and 1 second for input `1000002`.

# Answer
> 1 votes
# 05AB1E, 11 - 5 = 6 bytes

Taking that bonus of course :)

```
LŒʒOQ}é¤'+ý

```

Try it online!

```
LŒʒOQ}é¤'+ý  Argument: n
LŒ           Sublists of range 1 to n
  ʒOQ}       Filter by total sum equals n
      é¤     Get longest element
        '+ý  Join on '+'

```

# Answer
> 1 votes
# PHP, 70 bytes

```
while(fmod($q=sqrt(2*$argn+(++$p-.5)**2)-.5,1));print_r(range($p,$q));

```

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

increments `p` until it finds an integer solution for `argument==(p+q)*(q-p+1)/2`,
then prints the range from `p` to `q`.

# Answer
> 1 votes
# Husk, 12 - 5 = 7 bytes

```
J'+msḟo=¹ΣQḣ

```

Try it online!

Removing the first 5 bytes for joining, it still scores the same.

## Explanation

```
J'+msḟo=¹ΣQḣ
           ḣ range from 1..n
          Q  all possible sublists
     ḟ       get the first value which satisfies:
       =¹Σ   sum = input.
   ms        convert each number to string
J'+          join on '+'

```

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

```
L/X/H:-between(L,H,X).
N*Z:-1/A/N,A/X/N,findall(Y,A/Y/X,Z),sumlist(Z,N).

```

Try it online!

-4 bytes thanks to DLosc.

# Answer
> 1 votes
# Knight, 66 bytes

```
;=i+=a 0P W;=r""!>=a+1=b a=c iW!>0c;=c-c=b+1b;=r+r+"+"bI?0cQ Or 0

```

Try it online!

Annotated code:

```
;=i+ =a 0 PROMPT                        # set a to 0, i to input
WHILE ;=r "" !>(=a +1(=b a)) (=c i)     # set r to "", b to a, a to a+1, c to i, check if a less than c
  WHILE !< c 0                          # while c >= 0:
    ;=c (-c (=b +1b))                   # set b to b+1, c to c-b
    ;=r (+ r + " " b)                   # append b to r
    IF (? c 0) (QUIT OUTPUT r) 0        # if c is 0, output r and break; else, do nothing

```

# Answer
> 1 votes
# C (gcc), 66 bytes

```
i,j;f(n){for(i=j=0;n;)n+=n>0?--j:++i;for(;i+j;)printf("%d ",++i);}

```

Inspired by xnor's sliding window solution, keeps track of the ends of the window.

Try it online!

# Answer
> 1 votes
# 05AB1E, (10-5=) 5 bytes

```
Åœ.Δ¥P}'+ý

```

Try it online or verify all test cases.

**Explanation:**

```
Åœ        # Get all lists of positive integers that sum to the (implicit) input,
          # which is sorted from longest (all 1s) to shortest (just the number)
  .Δ      # Find the first list which is truthy for:
    ¥     #  Get the deltas/forward-differences of the list
     P    #  Take the product (only 1 is truthy in 05AB1E)
   }'+ý  '# After we've found a list: join it with "+" delimiter
          # (after which it is output implicitly as result)

```

# Answer
> 1 votes
# Thunno 2, 10 - 5 = 5 bytes

```
RƑæS=;h'+j

```

Try it online!

Port of tybocopperkettle's Vyxal answer.

#### Explanation

```
RƑæS=;h'+j  '# Implicit input
RƑ           # All sublists of [1..n]
  æ  ;       # Filtered by:
   S=        #  Sum equals input
      h      # First item
       '+j  '# Joined by "+"
             # Implicit output

```

# Answer
> 0 votes
# Python 3, ~~239~~ ~~236~~ ~~215~~ 203 bytes

This is a little cumbersome. I'll have to golf it down later.

```
def x(n):
 r=[n]
 for i in range(2,n):
  t=[]
  if i%2*(n%i<1):t=[j+n//i-i//2for j in range(i)]
  elif i%2<1and n%i==i//2:t=[j+n//i-i//2+1for j in range(i)]
  if t[:1]>[0]*(sum(t)==n):r+=t,
 return r[-1]

```

~~The `k` is because if you check `t[0]` on an empty `t`, Python makes rude noises at you. Again, this is in need of golfing.~~ Thanks to `t[:1]`, no more rude noises! You just need to check against another array.

# Answer
> 0 votes
# Japt, 33 bytes

This uses Dennis's Pyth technique, although it's considerably longer...

```
1oU à2 £W=Xg o1+Xg1¹x ¥U©W} rª ªU

```

Try it online! **Warning:** For larger inputs (\<= 20), it takes a while to finish, and freezes your browser until it does.

### Ungolfed and explanation

```
1oU à2 £    W=Xg o1+Xg1¹ x ¥ U© W} rª  ª U
1oU à2 mXYZ{W=Xg o1+Xg1) x ==U&&W} r|| ||U

          // Implicit: U = input integer
1oU à2    // Generate a range from 1 to U, and take all combinations of length 2.
mXYZ{     // Map each item X in this range to:
W=Xg o    //  Set variable W to the range of integers starting at the first item in X,
1+Xg1)    //  and ending at 1 + the second item in X.
x ==U&&W  //  If the sum of this range equals U, return W; otherwise, return false.
r||       // Reduce the result with the || operator, returning the first non-false value.
||U       // If this is still false, there are no consecutive ranges that sum to U,
          // so resort to U itself.
          // Implicit: output last expression

```

Bonus-earning version: (38 bytes - 5 = 33)

```
1oU à2 £W=Xg o1+Xg1¹x ¥U©W} rª ªU² q'+

```

# Answer
> 0 votes
# Julia, 92 bytes

```
x->(t=filter(i->all(j->j==1,diff(sort(i))),partitions(x));collect(t)[indmax(map(length,t))])

```

This is an anonymous function that accepts an integer and returns an array. To call it, give it a name, e.g. `f=x->...`.

Ungolfed:

```
function f(x::Integer)
    # Get all arrays of integers that sum to x
    p = partitions(x)

    # Filter these down to only consecutive runs by checking whether
    # all differences are 1
    t = filter(i -> all(j -> j == 1, diff(sort(i))), p)

    # Find the index of the longest element of t
    i = indmax(map(length, t))

    return collect(t)[i]
end

```

# Answer
> 0 votes
# Ruby, 94 bytes

```
->n{([*1..n].permutation(2).map{|i,j|[*i..j]if(i..j).reduce(:+)==n}-[p]).max_by{|k|k.size}||n}

```

**Ungolfed:**

```
-> n {
  ([*1..n].permutation(2).map { |i,j|   # Finds all the possible sets of size 2
     [*i..j] if(i..j).reduce(:+) == n   # Adds a set to an array if sum of the set is n.
   }-[p]                                # Removes nil from the array
  ).max_by { |k|                        # Finds the longest sequence
    k.size
  } || n                                # Returns n if no sequence found.
}

```

**Usage:**

```
->n{([*1..n].permutation(2).map{|i,j|[*i..j]if(i..j).reduce(:+)==n}-[p]).max_by{|k|k.size}||n}[25]
=> [3, 4, 5, 6, 7]

```

# Answer
> 0 votes
## Seriously, 53 - 5 = 48 bytes

```
,;;;╝`;u@n╟(D;)`n(XXk`iu@u@x;Σ╛=[])Ii`╗`ñ╜M`M;░p@X'+j

```

Hex Dump

```
2c3b3b3bbc603b75406ec728443b29606e2858586b60697540754
0783be4be3d5b5d29496960bb60a4bd4d604d3bb0704058272b6a

```

Try It Online!

It's the brute force approach, similar to Dennis's Pyth.

Everything up to the `k` just reads input `n` into register 1 and then creates the list `[[1],[2,2],[3,3,3],[4,4,4,4],...]` up to `n` `n`'s.

The next bit up to  is a function stored in register 0 that takes a pair, increments both elements, converts them to a range, finds the sum of the range, and checks whether that sum is the value in register 1. If it is, it returns the corresponding range, and if it's not, it returns an empty list.

The part up to the last occurrence of `M` maps a function over the fancy list of lists described above, doing `enumerate` on each list, then mapping the stored function over it. When it is done, we have a list of lists each of which is empty or a range which sums to `n`.

`;░` removes the empty lists. `p@X` takes the first list which remains (`0@E` would also work). `'+j` puts `+` between each number as it converts the list to a string for the bonus.

# Answer
> 0 votes
## ES6, 72 bytes

```
n=>{for(l=u=1;n;)n>0?n-=u++:n+=l++;return[...Array(u).keys()].slice(l);}

```

Straight port of @Cabbie407's awk solution, but without the formatting bonus, since it's a penalty here.

# Answer
> 0 votes
# Excel VBA, 119 - 5 = 114 Bytes

`Sub`routine that takes input `n` of expected type integer and outputs the longest sequence of consecutive numbers which sum to it to the cell `[A1]`

```
Sub a(n)
For i=1To n
s=0
For j=i To n
s=s+j
If s=n Then:For k=i To j-1:r=r &k &"+":Next:[A1]=r &j:End
Next
Next
End Sub

```

# Answer
> 0 votes
# Japt `-h`, 9 bytes

```
õ ã f@¶Xx

```

Try it

## Japt, 13-5 = 8 bytes

```
õ ã f@¶XxÃÌq+

```

Try it

# Answer
> 0 votes
# , 57 bytes

```
for(i in (n=scan()):1)for(j in n:i)if(sum(i:j)==n)x=i:j;x

```

Try it online!

# Answer
> 0 votes
# Retina, ~~36~~ 32 bytes

```
(^_+?|_\1)+$
$1 $#1*
vI`(_*) \1_

```

Try it online!

Input in unary `_`, output a newline-separated list of decimal numbers

# Answer
> 0 votes
# Desmos, 118 bytes

```
f(n)=[l[1]...l[2]]
l=∑_{a=1}^n∑_{b=a}^n[a,b]0^{([a...b].total-n)^2}∏_{c=2}^a∏_{d=c}^nsign([c-1...d].total-n)^2

```

100% can be golfed but whatever.

In theory this should work with any number as long as the output list has at most 10000 elements, but in reality, an input like \\$n=100\\$ is already very slow.

Try It On Desmos!

Try It On Desmos! - Prettified

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

```
[ dup [1,b] all-subseqs [ Σ = ] with find-last ]

```

Try it online!

---
Tags: code-golf, math, number, sequence, integer-partitions
---