title: Shortest path to open a letter lock

text:
# Question
Title: Shortest path to open a letter lock
This quite literally came to me in a dream.

A common combination padlock design has letters on the dials so you can set the combination to a word. Unfortunately, I can't read, but I can count. Considering I am in a hurry, send the shortest path around the dials to open the 4 letter lock, given the current letters and the correct combination.

The lock is set up so that the downward direction means going through the alphabet forwards

`A->B->...Y->Z->A...`

and upwards is in reverse

`B->A->Z->Y....C->B->A->Z...`

One turn refers to moving one letter in either direction.

## Input

Any of

* two strings `"Position", "Combo"`
* a list of strings `["Position", "Combo"]`
* A list of each character in the position, and a list for the combo `['p1', 'p2' 'p3', 'p4'], ['c1', 'c2', 'c3', 'c4']`

The order of position and combo may be switched but the letters cannot be rearranged or interleaved in any way.

## Output

A list of the number of turns and the directions in which to turn. The directions can be indicated however you want, but it must be consistent and it cannot be a number. It can be a single list of tuples, paired `[turns, direction]` or `[direction, turns]` or two lists, one of turns and one of directions as long as direction\[a\] corresponds to turns\[a\]. Positive/Negative for Up/Down works as well. You can use either direction for zero turns or equidistant letters

## Test cases:

```
[position, combo] -> [[turn[1], direction[1]], [t[2],d[2]], ...]
["NLWX", "GOLF"] -> [[7, up], [3, down], [11, up], [8, down]]
["CODE", "COOL"] -> [[0, up], [0, up], [11, down], [7, down]]
["AUGH", "NOPE"] -> [[13, up], [6, up], [9, down], [3, up]]

```

# Answer
> 9 votes
# Uiua 0.8.0, 10 bytes SBCS

```
-13◿26+13-

```

Try on Uiua Pad!

Outputs positive and negative values.

## 18 bytes SBCS

```
+@a↥0⊃±⌵-13◿26+13-

```

Try on Uiua Pad!

Outputs 2 arrays, values and letters. Up is "a" and down is "b".

## Explanation

```
-   # subtract the strings, get distances between letters
+13 # add 13
◿26 # mod 26
-13 # subtract 13
⊃±⌵ # get the signs and absolute values
↥0  # take the minimum with 0, turns -1 signs into 0
+@a # add "a" to the signs, makes up="a" and down="b"

```

# Answer
> 5 votes
# Jelly, 7 bytes

```
O_/æ%13

```

Try it online!

A monadic link taking a list of two strings and returning a list of integers with negative integers as down and positive as up.

## Explanation

```
O       | To codepoints
 _/     | Reduce by subtraction
   æ%13 | Symmetric mod 13

```

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

```
x=>y=>x.map((c,i)=>parseInt(c+57+y[i],36)%97%26-13)

```

Try it online!

Output pos/neg

# JavaScript (Node.js), 68 bytes

```
x=>y=>x.map((c,i)=>[i=(c=parseInt(c+57+y[i],36)%97%26-13)<0,i?-c:c])

```

Try it online!

> The directions can be indicated however you want, but it must be consistent and it cannot be a number.

I don't understand why but here `true` and `false` used

# Answer
> 3 votes
# Scala 3, ~~78~~ 75 bytes

A port of @l4m2's Javascript code in Scala.

Saved 3 bytes thanks to the comment of @l4m2

---

```
(x,y)=>x.zip(y).map{case(c,v)=>Integer.parseInt(s"${c}57${v}",36)%97%26-13}

```

Attempt This Online!

# Answer
> 3 votes
# , 38 bytes

```
\(s,t,`+`=utf8ToInt)(+s-+t--13)%%26-13

```

Attempt This Online!

Port of @Tbw's Uiua answer.

# , 42 bytes

```
\(s,t)strtoi(paste0(t,57,s),36)%%97%%26-13

```

Attempt This Online!

Port of @l4m2's JavaScript answer.

# , ~~73~~ 66 bytes

```
\(s,t,`+`=utf8ToInt)Map(\(x,a=c(x,x-26))a[order(abs(a))[1]],+s-+t)

```

Attempt This Online!

Straightforward (?) implementation of the task.

# Answer
> 3 votes
# 05AB1E, 11 bytes

```
Ç`-13+₂%13-

```

Port of *@Tbw*'s Uiua's answer, so also uses negative values for down and positive for up.

Try it online or verify all test cases.

**Explanation:**

```
Ç            # Convert both strings in the (implicit) input-pair to a list of codepoint
             # integers
 `           # Pop and push both integer-lists separated to the stack
  -          # Subtract the values at the same positions from one another
   13+       # Add 13
      ₂%     # Modulo-26
        13-  # Subtract 13
             # (after which the result is output implicitly)

```

# Answer
> 3 votes
# Perl 5 `-lF`, 48 bytes

```
say+($_=(ord shift@F)-ord)-($_>13)*26for<>=~/./g

```

Try it online!

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

```
13-26|13+-⍥⎕UCS

```

Try it on APLgolf!

A tacit function which takes strings on the left and right and returns an array of positive and negative values. Port of my Uiua answer, but we have to get from letters to numbers first. This is done using `⎕UCS`, which takes a string and converts to Unicode code points.

# Answer
> 2 votes
# Google Sheets, 45 bytes

```
=index(mod(code(A1:A4)-code(B1:B4)+13,26)-13)

```

Put the position in cells `A1:A4`, the combination in cells `B1:B4` and the formula in cell `C1`. The output will be in positive/negative integers.

Uses Tbw's method.

# Microsoft Excel for the web, 38 bytes

```
=MOD(CODE(A1:A4)-CODE(B1:B4)+13,26)-13

```

Only works in Excel versions that spill result arrays by default.

# Answer
> 2 votes
# Charcoal, 19 bytes

```
Ｉ⁻¹³﹪⁻¹³Ｅθ⁻℅ι℅§ηκ²⁶

```

Try it online! Link is to verbose version of code. Explanation: Similar to @Tbw's method, but subtracts the 13 in a different way to save bytes. (@l4m2's method would take 21 bytes in Charcoal.)

```
  ¹³                Literal integer `13`
 ⁻                  Vectorised subtract
      ¹³            Literal integer `13`
     ⁻              Vectorised subtract
         θ          First input
        Ｅ           Map over characters
            ι       Current character
           ℅        Ordinal
          ⁻         Subtract
               η    Second input
              §     Indexed by
                κ   Current index
             ℅      Ordinal
    ﹪               Vectorised modulo
                 ²⁶ Literal integer `26`
Ｉ                   Cast to string
                    Implicitly print

```

# Answer
> 1 votes
# Retina 0.8.2, 90 bytes

```
O$#`.
$.%`
¶

M!`..
(.).
$&-$1
%{`.*?([A-Z])(-?)(#*)\1.*
$2$.3
T`L`ZL`^.
T`ZL`L`.$
.-
#$&#

```

Try it online! Takes input on separate lines but link is to test suite that splits on commas for convenience. Explanation:

```
O$#`.
$.%`
¶

M!`..

```

Transpose the input.

```
(.).
$&-$1

```

Duplicate the starting letters, but prefixed with `-`s, to indicate these copies are the ones going backwards.

```
%{`

```

Repeat the rest of the script on each line separately.

```
.*?([A-Z])(-?)(#*)\1.*
$2$.3

```

If the current line contains two identical letters, record the count of how long it took with the sign if appropriate.

```
T`L`ZL`^.

```

Advance the first letter forwards.

```
T`ZL`L`.$

```

Wind the last letter backwards.

```
.-
#$&#

```

Increment the count.

---
Tags: code-golf, parsing
---


# Question
Title: Lockers vs. Crackers: The Five-Element Sequence
# The Challenge

A simple "spy versus spy" challenge.

Write a program with the following specifications:

1. The program may be written in any language but must not exceed 512 characters (as represented in a code block on this site).
2. The program must accept 5 signed 32-bit integers as inputs. It can take the form of a function that accepts 5 arguments, a function that accepts a single 5-element array, or a complete program that reads 5 integers from any standard input.
3. The program must output one signed 32-bit integer.
4. The program must return 1 if and only if the five inputs, interpreted as a sequence, match a specific arithmetic sequence of the programmer's choosing, called the "key". The function must return 0 for all other inputs.

An arithmetic sequence has the property that each successive element of the sequence is equal to its predecessor plus some fixed constant `a`.

For example, `25 30 35 40 45` is an arithmetic sequence since each element of the sequence is equal to its predecessor plus 5. Likewise, `17 10 3 -4 -11` is an arithmetic sequence since each element is equal to its precessor plus -7.

The sequences `1 2 4 8 16` and `3 9 15 6 12` are not arithmetic sequences.

A key may be any arithmetic sequence of your choosing, with the sole restriction that sequences involving integer overflow are not permitted. That is, the sequence *must* be strictly increasing, strictly decreasing, or have all elements equal.

As an example, suppose you choose the key `98021 93880 89739 85598 81457`. Your program must return 1 if the inputs (in sequence) match these five numbers, and 0 otherwise.

**Please note that the means of protecting the key should be of your own novel design. Also, probabilistic solutions that may return false positives with any nonzero probability are not permitted. In particular, please do not use any standard cryptographic hashes, including library functions for standard cryptographic hashes.**

# The Scoring

The shortest non-cracked submission(s) per character count will be declared the winner(s).

If there's any confusion, please feel free to ask or comment.

# The Counter-Challenge

All readers, including those who have submitted their own programs, are encouraged to "crack" submissions. A submission is cracked when its key is posted in the associated comments section. If a submission persists for 72 hours without being modified or cracked, it is considered "safe" and any subsequent success in cracking it will be ignored for sake of the contest.

See "Disclaimer" below for details on the updated cracking score policy.

Cracked submissions are eliminated from contention (provided they are not "safe"). They should not be edited. If a reader wishes to submit a new program, (s)he should do so in a separate answer.

The cracker(s) with the highest score(s) will be declared the winners along with the developers of the winning programs.

*Please do not crack your own submission.*

Best of luck. :)

# Leaderboard

Penultimate standings (pending safety of Dennis' CJam 49 submission).

### Secure Lockers

1. CJam 49, Dennis
2. CJam 62, Dennis *safe*
3. CJam 91, Dennis *safe*
4. Python 156, Maarten Baert *safe*
5. Perl 256, chilemagic *safe*
6. Java 468, Geobits *safe*

### Unstoppable Crackers

1. **Peter Taylor** \[Ruby 130, Java 342, Mathematica 146\*, Mathematica 72\*, CJam 37\]
2. Dennis \[Pyth 13, Python 86\*, Lua 105\*, GolfScript 116, C 239\*\]
3. Martin Büttner \[Javascript 125, Python 128\*, Ruby 175\*, Ruby 249\*\]
4. Tyilo \[C 459, Javascript 958\*\]
5. freddieknets \[Mathematica 67\*\]
6. Ilmari Karonen \[Python27 182\*\]
7. nitrous \[C 212\*\]

\*non-compliant submission

### Disclaimer (Updated 11:15 PM EST, Aug 26)

With the scoring problems finally reaching critical mass (given two thirds of the cracked submissions are thus far non-compliant), I've ranked the top crackers in terms of number of submissions cracked (primary) and total number of characters in compliant cracked submissions (secondary).

As before, the exact submissions cracked, the length of the submissions, and their compliant/non-compliant status are all marked so that readers may infer their own rankings if they believe the new official rankings are unfair.

My apologies for amending the rules this late in the game.

# Answer
> 4 votes
# CJam, 62 characters

```
"ḡꬼ쏉壥떨ሤ뭦㪐ꍡ㡩折量ⶌ팭뭲䯬ꀫ郯⛅彨ꄇ벍起ឣ莨ຉᆞ涁呢鲒찜⋙韪鰴ꟓ䘦쥆疭ⶊ凃揭"2G#b129b:c~

```

Stack Exchange is prone to mauling unprintable characters, but copying the code from this paste and pasting it in the CJam interpreter works fine for me.

### How it works

After replacing the Unicode string with an ASCII string, the following code gets executed:

```
" Push 85, read the integers from STDIN and collect everything in an array.               ";

85l~]

" Convert the array of base 4**17 digits into and array of base 2 digits.                 ";

4H#b2b

" Split into chunks of length 93 and 84.                                                  ";

93/~

" Do the following 611 times:

    * Rotate array A (93 elements) and B one element to the left.
    * B[83] ^= B[14]
    * T = B[83]
    * B[83] ^= B[0] & B[1] ^ A[23]
    * A[92] ^= A[26]
    * Rotate T ^ A[92] below the arrays.
    * A[92] ^= A[0] & A[1] ^ B[5].                                                        ";

{(X$E=^:T1$2<:&^2$24=^+\(1$26=^_T^@@1$2<:&^3$5=^+@}611*

" Discard the arrays and collects the last 177 generated bits into an array.              ";

;;]434>

" Convert the into an integer and check if the result is 922 ... 593.                     ";

2b9229084211442676863661078230267436345695618217593=

```

This approach uses Bivium-B (see Algebraic analysis of Trivium-like ciphers), a weakened version of the stream cipher Trivium.

The program uses the sequence of integers as initial state, updates the state 434 times (354 rounds achieve full diffusion) and generates 177 bit of output, which it compares to those of the correct sequence.

Since the state's size is precisely 177 bits, this *should* suffice to uniquely identify the initial state.

### Example run

```
$ echo $LANG
en_US.UTF-8
$ base64 -d > block.cjam <<< IgThuKHqrLzsj4nlo6XrlqjhiKTrrabjqpDqjaHjoanmipjvpb7itozuoIDtjK3rrbLul7bkr6zqgKvvjafpg6/im4XlvajqhIfrso3uprrotbfvmL/hnqPojqjguonhhp7mtoHujLPuipzlkaLpspLssJzii5npn6rpsLTqn5PkmKbspYbnlq3itorlh4Pmj60iMkcjYjEyOWI6Y34=
$ wc -m block.cjam
62 block.cjam
$ cjam block.cjam < block.secret; echo
1
$ cjam block.cjam <<< "1 2 3 4 5"; echo
0

```

# Answer
> 6 votes
# CJam, 91 characters

```
q~]KK#bD#"᫖࿼듋ޔ唱୦廽⻎킋뎢凌Ḏ끮冕옷뿹毳슟夫΢眘藸躦䪕齃噳卤"65533:Bb%"萗縤ᤞ雑燠Ꮖ㈢ꭙ㈶タ敫䙿娲훔쓭벓脿翠❶셭剮쬭玓ୂ쁬䈆﹌⫌稟"Bb=

```

Stack Exchange is prone to mauling unprintable characters, but copying the code from this paste and pasting it in the CJam interpreter works fine for me.

### How it works

After replacing the Unicode string with integers (by considering the characters digits of base 65533 numbers), the following code gets executed:

```
" Read the integers from STDIN and collect them in an array.                               ";

q~]

" Convert it into an integer by considering its elements digits of a base 20**20 number.   ";

KK#b

" Elevate it to the 13th power modulus 252 ... 701.                                        ";

D#
25211471039348320335042771975511542429923787152099395215402073753353303876955720415705947365696970054141596580623913538507854517012317194585728620266050701%

" Check if the result is 202 ... 866.                                                      ";

20296578126505831855363602947513398780162083699878357763732452715119575942704948999334568239084302792717120612636331880722869443591786121631020625810496866=

```

Since 13 is coprime to the totient of the modulus (the totient is secret, so you'll just have to trust me), different bases will generate different results, i.e., the solution is unique.

Unless someone can exploit the small exponent (13), the most efficient way of breaking this lock is to factorize the modulus (see RSA problem). I chose a 512-bit integer for the modulus, which should withstand 72 hours of factorization attempts.

### Example run

```
$ echo $LANG
en_US.UTF-8
$ base64 -d > lock.cjam <<< cX5dS0sjYkQjIgHuiJHhq5bgv7zrk4velOWUse6zjuCtpuW7veK7ju2Ci+uOouWHjOG4ju+Rh+uBruWGleyYt+u/ueavs+6boOyKn+Wkq86i55yY6Je46Lqm5KqV6b2D5Zmz75Wp5Y2kIjY1NTMzOkJiJSIB6JCX57ik4aSe74aS6ZuR54eg4Y+G44ii6q2Z44i244K/5pWr5Jm/5aiy7ZuU7JOt67KT7rO26IS/57+g4p2275+K7IWt5Ymu7Kyt546T4K2C7IGs5IiG77mM4quM56ifIkJiPQ==
$ wc -m lock.cjam
91 lock.cjam
$ cjam lock.cjam < lock.secret; echo
1
$ cjam lock.cjam <<< "1 2 3 4 5"; echo
0

```

# Answer
> 4 votes
# Python - 128

Let's try this one:

```
i=input()
k=1050809377681880902769L
print'01'[all((i>1,i[0]<i[4],k%i[0]<1,k%i[4]<1,i[4]-i[3]==i[3]-i[2]==i[2]-i[1]==i[1]-i[0]))]

```

(Expects the user to input 5 comma-separated numbers, e.g. `1,2,3,4,5`.)

# Answer
> 4 votes
# Java : 468

Input is given as `k(int[5])`. Bails early if not evenly spaced. Otherwise, it takes a bit figuring out if all ten hashes are correct. For large numbers, "a bit" can mean ten seconds or more, so it might dissuade crackers.

```
//golfed
int k(int[]q){int b=q[1]-q[0],i,x,y,j,h[]=new int[]{280256579,123883276,1771253254,1977914749,449635393,998860524,888446062,1833324980,1391496617,2075731831};for(i=0;i<4;)if(q[i+1]-q[i++]!=b||b<1)return 0;for(i=1;i<6;b=m(b,b/(i++*100),(1<<31)-1));for(i=0;i<5;i++){for(j=1,x=b,y=b/2;j<6;x=m(x,q[i]%100000000,(1<<31)-1),y=m(y,q[i]/(j++*1000),(1<<31)-1));if(x!=h[i*2]||y!=h[i*2+1])return 0;}return 1;}int m(int a,int b,int c){long d=1;for(;b-->0;d=(d*a)%c);return (int)d;}

// line breaks
int k(int[]q){
    int b=q[1]-q[0],i,x,y,j,
    h[]=new int[]{280256579,123883276,1771253254,1977914749,449635393,
                  998860524,888446062,1833324980,1391496617,2075731831};
    for(i=0;i<4;)
        if(q[i+1]-q[i++]!=b||b<1)
            return 0;
    for(i=1;i<6;b=m(b,b/(i++*100),(1<<31)-1));
    for(i=0;i<5;i++){
        for(j=1,x=b,y=b/2;j<6;x=m(x,q[i]%100000000,(1<<31)-1),y=m(y,q[i]/(j++*1000),(1<<31)-1));
        if(x!=h[i*2]||y!=h[i*2+1])
            return 0;
    }
    return 1;
}
int m(int a,int b,int c){
    long d=1;for(;b-->0;d=(d*a)%c);
    return (int)d;
}

```

# Answer
> 4 votes
# Python, 147

Edit: shorter version based on Dennis' comment. I updated the sequence too to avoid leaking any information.

```
def a(b):
    c=1
    for d in b:
        c=(c<<32)+d
    return pow(7,c,0xf494eca63dcab7b47ac21158799ffcabca8f2c6b3)==0xa3742a4abcb812e0c3664551dd3d6d2207aecb9be

```

Based on the discrete logarithm problem which is believed to be uncrackable, however the prime I'm using is probably too small to be secure (and it may have other issues, I don't know). And you can brute-force it of course, since the only unknowns are two 32-bit integers.

# Answer
> 4 votes
# Java : 342

```
int l(int[]a){String s=""+(a[1]-a[0]);for(int b:a)s+=b;char[]c=new char[11];for(char x:s.toCharArray())c[x<48?10:x-48]++;for(int i=0;i<11;c[i]+=48,c[i]=c[i]>57?57:c[i],i++,s="");for(int b:a)s+=new Long(new String(c))/(double)b;return s.equals("-3083.7767567702776-8563.34366442527211022.4345579010483353.1736981951231977.3560837512646")?1:0;}

```

Here's a string-based locker that depends on both the input character count and the specific input. The sequence *might* be based on obscure pop culture references. Have fun!

A bit ungolfed:

```
int lock(int[]a){
    String s=""+(a[1]-a[0]);
    for(int b:a)
        s+=b;
    char[]c=new char[11];
    for(char x:s.toCharArray())
        c[x<48?10:x-48]++;
    for(int i=0;i<11;c[i]+=48,
                     c[i]=c[i]>57?57:c[i],
                     i++,
                     s="");
    for(int b:a)
        s+=new Long(new String(c))/(double)b;
    return s.equals("-3083.7767567702776-8563.34366442527211022.4345579010483353.1736981951231977.3560837512646")?1:0;
}

```

# Answer
> 3 votes
# Javascript 125

This one should be cracked pretty quickly. I'll follow up with something stronger.

```
function unlock(a, b, c, d, e)
{
    return (e << a == 15652) && (c >> a == 7826) && (e - b == d) && (d - c - a == b) ? 1 : 0;
}

```

# Answer
> 3 votes
# Ruby, 175

```
a=gets.scan(/\d+/).map(&:to_i)
a.each_cons(2).map{|x,y|x-y}.uniq[1]&&p(0)&&exit
p a[2]*(a[1]^a[2]+3)**7==0x213a81f4518a907c85e9f1b39258723bc70f07388eec6f3274293fa03e4091e1?1:0

```

Unlike using a cryptographic hash or `srand`, this is provably unique (which is a slight clue). Takes five numbers via STDIN, delimited by any non-digit, non-newline character or characters. Outputs to STDOUT.

# Answer
> 3 votes
# Mathematica ~~80~~ 67

```
f=Boole[(p=NextPrime/@#)-#=={18,31,6,9,2}&&BitXor@@#~Join~p==1000]&

```

Running:

```
f[{1,2,3,4,5}] (* => 0 *)

```

Probably pretty easy to crack, might also have multiple solutions.

**Update:** Improved golfing by doing what Martin Büttner suggested. Functionality of the function and the key hasn't changed.

# Answer
> 3 votes
## GolfScript (116 chars)

Takes input as space-separated integers.

```
~]{2.5??:^(&}%^base 2733?5121107535380437850547394675965451197140470531483%5207278525522834743713290685466222557399=

```

# Answer
> 3 votes
# C 459 bytes

# SOLVED BY Tyilo -- READ EDIT BELOW

```
int c (int* a){
int d[4] = {a[1] - a[0], a[2] - a[1], a[3] - a[2], a[4] - a[3]};
if (d[0] != d[1] || d[0] != d[2] || d[0] != d[3]) return 0;
int b[5] = {a[0], a[1], a[2], a[3], a[4]};
int i, j, k;
for (i = 0; i < 5; i++) {
for (j = 0, k = 2 * i; j < 5; j++, k++) {
k %= i + 1;
b[j] += a[k];
}
}
if (b[0] == 0xC0942 - b[1] &&
b[1] == 0x9785A - b[2] &&
b[2] == 0x6E772 - b[3] &&
b[3] == 0xC0942 - b[4] &&
b[4] == 0xB6508 - b[0]) return 1;
else return 0;
}

```

We need someone to write a C solution, don't we? I'm not impressing anybody with length, I'm no golfer. I hope it's an interesting challenge, though!

I don't think there's an obvious way to crack this one, and I eagerly await all attempts! I know this solution to be unique. Very minimal obfuscation, mostly to meet length requirements. This can be tested simply:

```
int main(){
    a[5] = {0, 0, 0, 0, 0} /* your guess */
    printf("%d\n", c(a));
    return 0;
}

```

P.S. There's a significance to `a[0]` as a number in its own right, and I'd like to see somebody point it out in the comments!

# EDIT:

Solution: `6174, 48216, 90258, 132300, 174342`

A note about cracking:

While this is not the method used (see the comments), I did happen to crack my own cipher with a very easy bruteforce. I understand now it is vitally important to make the numbers large. The following code can crack any cipher where `upper_bound` is a known upper bound for `a[0] + a[1] + a[2] + a[3] + a[4]`. The upper bound in the above cipher is `457464`, which can be derived from the system of equations of `b[]` and some working-through of the algorithm. It can be shown that `b[4] = a[0] + a[1] + a[2] + a[3] + a[4]`.

```
int a[5];
for (a[0] = 0; a[0] <= upper_bound / 5; a[0]++) {
    for (a[1] = a[0] + 1; 10 * (a[1] - a[0]) + a[0] <= upper_bound; a[1]++) {
        a[2] = a[1] + (a[1] - a[0]);
        a[3] = a[2] + (a[1] - a[0]);
        a[4] = a[3] + (a[1] - a[0]);
        if (c(a)) {
            printf("PASSED FOR {%d, %d, %d, %d, %d}\n", a[0], a[1], a[2], a[3], a[4]);
        }
    }
    printf("a[0] = %d Checked\n", a[0]);
}

```

With `a[0] = 6174`, this loop broke my work in a little under a minute.

# Answer
> 2 votes
## Python27, ~~283~~ 182

Alright, I am very confident in my locker, however it is quite long as I've added 'difficult to reverse' calculations to the input, to make it well - difficult to reverse.

```
import sys
p=1
for m in map(int,sys.argv[1:6]):m*=3**len(str(m));p*=m<<sum([int(str(m).zfill(9)[-i])for i in[1,3,5,7]])
print'01'[p==0x4cc695e00484947a2cb7133049bfb18c21*3**45<<101]

```

edit: Thanks to colevk for the further golfing. I realized during editing that there was a bug as well as a flaw in my algorithm, maybe I'll have better luck next time.

# Answer
> 2 votes
**Mathematica ~~142~~ 146**

**EDIT**: key wasn't unique, added 4 chars, now it is.

```
n=NextPrime;
f=Boole[
    FromDigits /@ (
        PartitionsQ[n@(237/Plus@##) {1, ##} + 1] & @@@
            IntegerDigits@n@{Plus@##-37*Log[#3],(#1-#5)#4}
    ) == {1913001154,729783244}
]&

```

(Spaces and newlines added for readability, not counted & not needed).

Usage:

```
f[1,2,3,4,5]   (* => 0 *)

```

# Answer
> 2 votes
# CJam, 49 characters

```
"腕옡裃䃬꯳널֚樂律ࡆᓅ㥄뇮┎䔤嬣ꑙ䘿휺ᥰ籃僾쎧諯떆Ἣ餾腎틯"2G#b[1q~]8H#b%!

```

Try it online.

### How it works

```
" Push a string representing a base 65536 number and convert it to an integer.            ";

"腕옡裃䃬꯳널֚樂律ࡆᓅ㥄뇮┎䔤嬣ꑙ䘿휺ᥰ籃僾쎧諯떆Ἣ餾腎틯"2G#b

" Prepend 1 to the integers read from STDIN and collect them into an array.               ";

[1q~]

" Convert that array into an integer by considering it a base 2**51 number.               ";

8H#b

" Push the logical NOT of the modulus of both computed integers.                          ";

%!

```

The result will be 1 if and only if the second integer is a factor of the first, which is a product of two primes: the one corresponding to the secret sequence and another that doesn't correspond to any valid sequence. Therefore, the solution is unique.

Factorizing a 512 bit integer isn't *that* difficult, but I hope nobody will be able to in 72 hours. My previous version using a 320 bit integer has been broken.

### Example run

```
$ echo $LANG
en_US.UTF-8
$ base64 -d > flock512.cjam <<< IuiFleyYoeijg+SDrOqvs+uEkNaa76a/5b6L4KGG4ZOF76Gi46WE64eu4pSO5JSk5ayj6pGZ5Ji/7Zy64aWw57GD5YO+7I6n6Kuv65aG7qK04byr6aS+6IWO7rSn7YuvIjJHI2JbMXF+XThII2IlIQ==
$ wc -m flock512.cjam
49 flock512.cjam
$ cjam flock512.cjam < flock512.secret; echo
1
$ cjam flock512.cjam <<< "1 2 3 4 5"; echo
0

```

# Answer
> 1 votes
# Cracked by @Dennis in 2 hours

---

Just a simple one to get things started - I fully expect this to be quickly cracked.

# Pyth, 13

```
h_^ZqU5m-CGdQ

```

Takes comma separated input on STDIN.

Run it like this (-c means take program as command line argument):

```
$ echo '1,2,3,4,5' | python3 pyth.py -c h_^ZqU5m-CGdQ
0

```

Fixed the program - I had not understood the spec.

This language might be too esoteric for this competition - If OP thinks so, I will remove it.

# Answer
> 1 votes
# Lua 105

I suspect it won't be long before it's cracked, but here we go:

```
function f(a,b,c,d,e)
   t1=a%b-(e-2*(d-b))
   t2=(a+b+c+d+e)%e
   t3=(d+e)/2
   print(t1==0 and t2==t3 and"1"or"0")
end

```

(spaces added for clarity, but are not part of count)

# Answer
> 1 votes
## Perl - 256

```
sub t{($z,$j,$x,$g,$h)=@_;$t="3"x$z;@n=(7,0,split(//,$g),split(//,$h),4);@r=((2)x6,1,1,(2)x9,4,2,2,2);$u=($j+1)/2;for$n(0..$#r+1){eval{substr($t,$j,1)=$n[$n]};if($@){print 0; return}$j+=$r[$n]*$u}for(1..$x){$t=pack'H*',$t;}eval$t;if($@||$t!~/\D/){print 0}}

```

I had to put in a lot of error handling logic and this can definitely be golfed down a lot more. It will print a `1` when you get the right five numbers. It will **hopefully** print a `0` for everything else (might be errors or nothing, I don't know). If anyone wants to help improve the code or golf it more, feel free to help out!

---

## Call with:

```
t(1,2,3,4,5);

```

# Answer
> 1 votes
## Ruby - 130

Based on Linear Feedback Shift Register. Inputs by command line arguments.
Should be unique based on the nature of LFSRs. Clue: ascending and all positive.

Will give more clues if no one solves it soon.

```
x=($*.map{|i|i.to_i+2**35}*'').to_i
(9**8).times{x=((x/4&1^x&1)<<182)+x/2}
p x.to_s(36)=="qnsjzo1qn9o83oaw0a4av9xgnutn28x17dx"?1:0

```

# Answer
> 1 votes
# Ruby, 249

```
a=gets.scan(/\d+/).map(&:to_i)
a.each_cons(2).map{|x,y|x-y}.uniq[1]&&p(0)&&exit
r=(a[0]*a[1]).to_s(5).tr'234','(+)'
v=a[0]<a[1]&&!r[20]&&(0..3).select{|i|/^#{r}$/=~'%b'%[0xaa74f54ea7aa753a9d534ea7,'101'*32,'010'*32,'100'*32][i]}==[0]?1:0rescue 0
p v

```

Should be fun. Who needs math?

# Answer
> 1 votes
# C 93 bytes

A simple hash. To follow the rule of unique solution, I bruteforced all the candidates, which took quite some core-hours. Of course the solution can be found in the same way.

The function `f` accepts a pointer to the 5 input integers and outputs 1 for the unique solution, 0 otherwise.

```
i=1e5;f(int*x){for(;--i;)x[i&3]+=(x[4]^=x[i&3])*9>>3;return!memcmp(x,"U|]v-W^Scv1(-8V8",16);}

```

For more adventurous hackers, here's a variant with 64-bit security`*` (89 bytes), which I could not verify to have a unique solution due to too big search space (but the chance of it happening is less than 1 in a billion).

```
i=1e5;f(int*x){for(;--i;)x[i&3]+=(x[4]^=x[i&3])*9>>3;return!memcmp(x,"'=P(=31qlite",12);}

```

`*` 64-bit security meaning 2^64 function calls. The number of required bit operations is quite bigger.

# Answer
> 0 votes
# Javascript 958

Converts the inputs to a number of data types and performs some manipulations relevant to each data type along the way. Should be fairly easily reversed for anyone that takes the time.

```
function encrypt(num)
{
    var dateval = new Date(num ^ (1024-1) << 10);

    dateval.setDate(dateval.getDate() + 365);

    var dateString = (dateval.toUTCString() + dateval.getUTCMilliseconds()).split('').reverse().join('');

    var result = "";

    for(var i = 0; i < dateString.length; i++)
        result += dateString.charCodeAt(i);

    return result;
}

function unlock(int1, int2, int3, int4, int5)
{
    return encrypt(int1) == "5549508477713255485850495848483249555749321109774324948324410511470" && encrypt(int2) == "5756568477713252485848495848483249555749321109774324948324410511470" && encrypt(int3) == "5149538477713248485856485848483249555749321109774324948324410511470" && encrypt(int4) == "5356498477713256535853485848483249555749321109774324948324410511470" && encrypt(int5) == "5748568477713251535851485848483249555749321109774324948324410511470" ? 1 : 0;
}

```

# Answer
> 0 votes
## C, 239 (Cracked by Dennis)

Go here for my updated submission.

Could probably be golfed a little more thoroughly. Admittedly, I haven't taken the time to prove the key is unique (it probably isn't) but its definitely on the order of a hash collision. If you crack it, please share your method :)

```
p(long long int x){long long int i;x=abs(x);
for (i=2;i<x;i++) {if ((x/i)*i==x) return 0;}return 1;}
f(a,b,c,d,e){char k[99];long long int m;sprintf(k,"%d%d%d%d%d",e,d,c,b,a);
sscanf(k,"%lld",&m);return p(a)&&p(b)&&p(c)&&p(d)&&p(e)&&p(m);}

```

# Answer
> 0 votes
# C, 212 by Orby -- Cracked

https://codegolf.stackexchange.com/a/36810/31064 by Orby has at least two keys:

```
13 103 193 283 373
113 173 233 293 353

```

Orby asked for the method I used to crack it. Function p checks whether x is prime by checking `x%i==0` for all i between 2 and x (though using `(x/i)*i==x` instead of `x%i==0`), and returns true if x is a prime number. Function f checks that all of a, b, c, d and e are prime. It also checks whether the number m, a concatenation of the decimal representations of e, d, c, b and a (in that order), is prime. The key is such that a,b,c,d,e and m are all prime.

Green and Tao (2004) show that there exist infinitely many arithmetic sequences of primes for any length k, so we just need to look for these sequences that also satisfy m being prime. By taking long long as being bounded by -9.223372037e+18 and 9.223372037e+18, we know that for the concatenated string to fit into long long, the numbers have an upper bound of 9999. So by using a python script to generate all arithmetic sequences within all primes \< 10000 and then checking whether their reverse concatenation is a prime, we can find many possible solutions.

For some reason I came up with false positives, but the two above are valid according to the program. In addition there may be solutions where e is negative and the rest are positive (p uses the modulus of x), but I didn't look for those.

The keys I gave are all arithmetic sequences but Orby's script doesn't appear to actually require the inputs to be an arithmetic sequence, so there may be invalid keys too.

# Answer
> 0 votes
# MATLAB: Apparently invalid

Very simple, you just have to generate the right random number.

```
function ans=t(a,b,c,d,e)
rng(a)
r=@(x)rng(rand*x)
r(b)
r(c)
r(d)
r(e)
rand==0.435996843156676

```

It can still error out, but that shouldn't be a problem.

# Answer
> 0 votes
# MATLAB (with Symbolic Toolbox), 173 characters

This isn't an official entry and won't count towards anyone's cracking score, but it will net you mad bragging rights. ;)

```
function b=L(S),c=sprintf('%d8%d',S(1),S(2)-S(1));b=numel(unique(diff(S)))==1&&numel(c)==18&&all(c([8,9])==c([18,17]))&&isequal(c,char(sym(sort(c,'descend'))-sym(sort(c))));

```

The symbolic toolbox is only required to handle subtraction of big integers.

Brute forcing it should be a dog, but if you're familiar with the series it involves, the solution is trivial.

# Answer
> 0 votes
# Python 2 (91)

**Edit:** This isn't allowed because the argument for uniqueness is probabilistic. I give up.

---

```
s=3
for n in input():s+=pow(n,s,7**58)
print s==0x8b5ca8d0cea606d2b32726a79f01adf56f12aeb6e

```

Takes lists of integers as input, like `[1,2,3,4,5]`.

The loop is meant to operate on the inputs in an annoying way, leaving a tower of sums and exponents. The idea is like discrete log, but with messy complication instead of mathematical simplicity. Maybe the compositeness of the of the modulus is a vulnerability, in which case I could make it something like `7**58+8`.

I don't really know how I'd prove that my key is the only one, but the range of outputs is at least 10 times bigger than the range of inputs, so probably? Though maybe only a small fraction of potential outputs are achievable. I could always increase the number of digits at the cost of characters. I'll leave it up to you to decide what's fair.

Happy cracking!

# Answer
> 0 votes
# Mathematica - 72

Version 2 of my script, with the same key as the one intended for my version 1.

This basically removes negative prime numbers for `NextPrime`.

```
f=Boole[(p=Abs[NextPrime/@#])-#=={18,31,6,9,2}&&BitXor@@#~Join~p==1000]&

```

Running:

```
f[{1,2,3,4,5}] (* => 0 *)

```

# Answer
> 0 votes
# Python, 86 characters

```
a,b,c,d,e=input()
print 1if(a*c^b*e)*d==0xd5867e26a96897a2f80 and b^d==48891746 else 0

```

Enter the numbers like `1,2,3,4,5`.

```
> python 36768.py <<< "1,2,3,4,5"
0
> python 36768.py <<< "[REDACTED]"
1

```

# Answer
> 0 votes
# CJam, 37 characters (broken)

```
"煷➻捬渓类ⶥ땙ዶ꾫㞟姲̷ᐂ㵈禙鰳쥛忩蔃"2G#b[1q~]4G#b%!

```

Try it online.

### How it works

See my new answer.

### Example run

```
$ echo $LANG
en_US.UTF-8
$ base64 -d > flock.cjam <<< IueFt+Keu+aNrOa4k+exu+K2peuVmeGLtuq+q+Oen+Wnsu6AhMy34ZCC47WI56aZ6bCz7KWb5b+p6JSDIjJHI2JbMXF+XTRHI2IlIQ==
$ wc -m flock.cjam
37 flock.cjam
$ cjam flock.cjam < flock.secret; echo
1
$ cjam flock.cjam <<< "1 2 3 4 5"; echo
0

```

# Answer
> 0 votes
# Python, 78

(Cracked by Tyilo in 14 mins)

Fun!

```
def L(a): return 1 if a==[(i-i**6) for i in bytearray(' ','utf-8')] else 0

```

Okay, it doesn't display properly here :(

Expects a list of five numbers, eg. \[1,2,3,4,5\]

# Answer
> -2 votes
## C, 212 (Cracked)

This is the same idea as my previous submission, golfed more thoroughly, with a bug corrected that passed 0,0,0,0,0 (Thanks to Dennis for pointing out the bug). Compile with -std=c99.

```
#define L long long
p(L x){x=abs(x);for(L i=2;i<x;i++){if((x/i)*i==x)return 0;}return(x>1);}
f(a,b,c,d,e){char k[99];L m;sprintf(k,"%d%d%d%d%d",e,d,c,b,a);sscanf(k,"%lld",&m);
return p(a)&p(b)&p(c)&p(d)&p(e)&p(m);}

```

# Answer
> -2 votes
# Python 3 (152)

**Edit 2:** I'm withdrawing this entry because it accepting the correct key seems to depend on hardware or version specifics, which would be unfair to crackers. On online Python 3 interpreters I tried, low-significance bits of the result differed slightly, suggesting the algorithm is sensitive to the exact hardware implementation of arithmetic.

**Edit:** Made a much longer target to make uniqueness likely given 160 bits of input. Unfortunately, now this target takes over half my characters. This means that this style of submission is unfortunately largely a compression contest.

```
def f(l,a=[0]):
 for n in l:a+=[(.8+.6j)**(n+a[-1])]
 return a[2::2]==[-0.20857691594748845+0.9907381787645837j,-0.7480510203178323-0.0856921111325014j]

```

Nothing systematic, just some annoying mangling with complex exponents.

---
Tags: code-golf, sequence, obfuscation, cops-and-robbers
---


title: Semi-Diagonal Alphabet

text:
# Question
Title: Semi-Diagonal Alphabet
Given a letter of the English alphabet, your task is to build a semi-diagonal alphabet to the input.

## How to build a Semi-Diagonal alphabet?

**Brief Description**: First, you take the position of the letter in the alphabet, `P` (`P` is 1-indexed here). Then, you print each letter until the input (inclusive) on a line, preceded by `P-1` and repeat that letter `P` times, interleaving with spaces.

**Examples**:

* Given `F`, your program should output:

```
A
 B B
  C C C
   D D D D
    E E E E E
     F F F F F F

```
* Given `K`, your program should output:

```
A
 B B
  C C C
   D D D D
    E E E E E
     F F F F F F
      G G G G G G G
       H H H H H H H H
        I I I I I I I I I
         J J J J J J J J J J
          K K K K K K K K K K K

```
* Given `A`, your program should output:

```
A

```

## Rules

* You may choose either lowercase or uppercase characters, but that should be consistent.
* You may have extraneous spaces as follows:

+ One consistent leading space (on each line).
    + A trailing or leading newline(s).
    + Trailing spaces.
* Input and output can be taken by any standard mean, and default loopholes apply.
* You are allowed to output a list of lines instead, as long as you also provide the version.
* This is , so the shortest code in bytes wins!

*Inspired by this challenge*.

# Answer
# Python 3, 59 bytes

```
lambda l:[' '*i+'%c '%(i+65)*-~i for i in range(ord(l)-64)]

```

Try it online!

# Python 3, 61 bytes

```
lambda l:[' '*i+-~i*(chr(i+65)+' ')for i in range(ord(l)-64)]

```

Try it online! (link to pretty-print version)
> 10 votes

# Answer
# Python 2, ~~63~~ ~~61~~ 59 bytes

*-2 bytes thanks to Rod. -2 bytes thanks to Felipe Nardi Batista.*

```
i=1
exec"print' '*i+'%c '%(i+64)*i;i+=1;"*(ord(input())-64)

```

Try it online!
> 9 votes

# Answer
# C, 89 bytes

```
i,j;f(l){for(i=64;i++<l&&printf("%*c ",i-64,i);puts(""))for(j=i-65;j--;)printf("%c ",i);}

```

Try it online!
> 8 votes

# Answer
# PowerShell, ~~45~~ 42 bytes

```
65..$args[0]|%{" "*$i+++"$([char]$_) "*$i}

```

Try it online!

Takes input as a literal char, then loops up through the capitals to that point, each iteration prepending the appropriate number of spaces and then the char\space hybrid.

*Saved 3 bytes thanks to TessellatingHeckler.*
> 7 votes

# Answer
# JavaScript (ES6), 85 bytes

Works in lower case for both input and output. Outputs a leading space and a trailing space on each line.

```
f=(c,k=10,C=k.toString(36),r=s=>`${s} `.repeat(k-9))=>r``+r(C)+(C==c?'':`
`+f(c,k+1))

```

### Demo

```
f=(c,k=10,C=k.toString(36),r=s=>`${s} `.repeat(k-9))=>r``+r(C)+(C==c?'':`
`+f(c,k+1))

O.innerText = f('m')
```

```
<pre id=O>
```
> 5 votes

# Answer
# APL (Dyalog), 26 bytes

Prompts for scalar character. Prints list of lines.

```
(∊⍴∘'',' ',¨⍨⊢⍴⊃∘⎕A)¨⍳⎕A⍳⎕

```

Try it online! (has ASCII art version at one additional byte)

prompt for input

`⎕A⍳` find **ɩ**ndex in **A**lphabet

first that many **ɩ**ntegers

`(` apply the following tacit function to each :

`⊃∘⎕A` pick the argument'th letter letter from the **A**lphabet

`⊢⍴` cyclically reshape it to the argument length

`' ',¨⍨` append a space to each

`⍴∘'',` prepend a string of argument length (padded with spaces)

**ϵ**nlist (flatten)

---

The ASCII art version just has a  on the very left; mix list of strings into table of characters.
> 5 votes

# Answer
## Perl 5, 31 bytes

**30 bytes code + 1 for `-l`.**

```
print$"x$-,"$_ "x++$-for A..<>

```

Try it online!
> 4 votes

# Answer
# Dyalog APL, 38 bytes

```
{↑{(y/' '),(2×y←⎕A⍳⍵)⍴⍵,' '}¨⎕A↑⍨⎕A⍳⍵}

```

Try it online!

**How?**

`⎕A↑⍨` \- take the alphabet until

`⎕A⍳⍵` \- the input character

`¨` \- for each char

`⍵,' '` \- take the char and a space

`(...)⍴` \- reshape to

`2×y←⎕A⍳⍵` \- twice the index of the char in the alphabet

`(y/' ')` \- and prepend index-of-char spaces

\- then flatten
> 3 votes

# Answer
# 05AB1E, 10 bytes

```
A¹¡н«ðâƶāú

```

Try it online!

-2 thanks to Adnan.

Append `»` to make it print in separate lines.
> 3 votes

# Answer
# , ~~28, 26, 25~~, 23 bytes (Competing)

```
¬A[/a
lDÓ./& ò
ò-Ûä$Û>

```

Try it online!

Note that although I have been planning on adding certain features for a long time, this challenge was what convinced me to finally do it.

The output contains one leading space on each line and one trailing newline.

Hexdump:

```
00000000: ac41 5b2f 1261 0a6c 44d3 2e2f 2620 f20a  .A[/.a.lD../& ..
00000010: f22d dbe4 24db 3e                        .-..$.>

```

Explanation:

```
¬A[         " Insert 'ABCDEFGHIJKLMNOPQRSTUVWXYZ['
   /        " Search for...
    <C-r>a  "   The input
l           " Move one character to the right
 D          " And delete every character after the cursor
  Ó         " Search for...
   .        "   Any character
    /       " And replace it with...
     & ò    "   That character followed by a space and a newline
ò           " Recursively...
 -          "   Move to the beginning of the next line up
  Ûä$       "   Make *line number* copies of the current line
     Û>     "   And indent this line by *line number* spaces

```
> 3 votes

# Answer
# APL (Dyalog Classic), 26 bytes

```
{↑{(≠\⍵<⍳3×⍵)\⍵⊃⎕A}¨⍳⎕A⍳⍵}

```

Try it online!

### Explanation

```
                      ⍳⎕A⍳⍵  generate indexes up to position of right arg ⍵
{                   }¨       on each index apply function
   (≠\⍵<⍳3×⍵)                generate boolean mask for expansion (each line has a length 3 times its index ⍵, starting with ⍵ blanks and then alternating letter blank)
             \⍵⊃⎕A          expand character in position ⍵
 ↑                            mix result into text matrix

```
> 3 votes

# Answer
# R,  94 88 bytes

-6 bytes thanks to Giuseppe

```
function(x,l=LETTERS)for(i in 1:match(x,l))cat(rep(' ',i-1),rep(paste(l[i],' '),i),'\n')}

```

Ungolfed:

```
f=function(x,l=letters){
  for(i in 1:which(l==x)){
    A=paste(l[i],' ')
    cat(rep(' ',i-1),rep(A,i),'\n')
  }
}

```
> 3 votes

# Answer
## Haskell, ~~52~~ 44 bytes

```
f k=[[" ",s:" "]>>=(['A'..s]>>)|s<-['A'..k]]

```

Returns a list of lines.

Try it online!

```
f k=                  -- main function is f, input parameter k
  [   |s<-['A'..k]]   -- for each s from ['A'..k]
     >>=              -- map (and collect the results in a single string) the function:
         (['A'..s]>>) --  replace each element in ['A'..s] with
    [  ,  ]           --  over the list, containing
     " "              --   a single space to get the indent
        s:" "         --   s followed by space to get the letter sequence

```

Edit: @jferard: saved three bytes. Thanks!
> 3 votes

# Answer
## Husk, 13 bytes

```
z+ḣ∞øzRNC1…'A

```

Takes a character in single quotes as command line argument, prints result to STDOUT. Try it online!

## Explanation

I'm exploiting the way Husk prints lists of lists of strings: join inner lists with spaces and outer lists with newlines.

```
z+ḣ∞øzRNC1…'A  Implicit input, say 'C'
          …'A  Range from A: "ABC"
        C1     Cut into strings of length 1: ["A","B","C"]
     z N       Zip with positive integers
      R        using repetition: x = [["A"],["B","B"],["C","C","C"]]
   ∞ø          The empty string repeated infinitely: ["","","",...
  ḣ            Prefixes: [[],[""],["",""],["","",""],...
z+             Zip with x using concatenation: [["A"],["","B","B"],["","","C","C","C"]]
               Implicitly join each inner list with spaces, join the resulting strings with newlines and print.

```
> 3 votes

# Answer
# Japt `-R`, ~~24~~ ~~23~~ ~~17~~ 15 bytes

Outputs an array, includes a leading newline and a leading & trailing space on each line.

```
IòUc ÏçSiXd¹iYç

```

Test it

* 1 byte saved with help from Oliver and a further 6 thanks to him pointing out a better way to generate the initial array.
> 2 votes

# Answer
# 05AB1E, ~~15~~ ~~14~~ 13 bytes

Saved 1 byte thanks to *Adnan*

```
A¹¡н«ƶ€S»¶¡āú»

```

Try it online! or the Ascii art version

**Explanation**

```
A                # push lowercase alphabet
 ¹¡              # split at input
   н             # get the first part
    «            # append the input
     ƶ           # repeat each a number of times corresponding to its 1-based index
      €S         # split each to a list of chars
        »        # join on spaces and newlines
         ¶¡      # split on newlines
           āú    # prepend spaces to each corresponding to its 1-based index
             »   # join on newlines

```
> 2 votes

# Answer
# JavaScript (ES8), 92 bytes

```
c=>(g=n=>n>9?[...g(n-1),`${n.toString(36)} `.repeat(n-=9).padStart(n*3)]:[])(parseInt(c,36))

```

Uses lowercase letters. Lines have one leading and one trailing space. Returns an array of lines.

## Test Snippet

```
let f=

c=>(g=n=>n>9?[...g(n-1),`${n.toString(36)} `.repeat(n-=9).padStart(n*3)]:[])(parseInt(c,36))

;O.innerText=f("k").join`\n`
```

```
<pre id=O></pre>
```
> 2 votes

# Answer
# APL (Dyalog Unicode), 22 bytesSBCS

```
⍕⍪⊢∘⊂\2,.↑⍉⍴⍨⌸⎕a↑⍨⎕a⍳⍞

```

Try it online!

Uses `⎕io←1`. Prints a leading space, which is allowed.
> 2 votes

# Answer
# QBasic, ~~79~~ ~~74~~ 72 bytes

*Thanks to Taylor Scott for byte savings (twice!)*

```
FOR i=1TO ASC(INPUT$(1))-64
?TAB(i)
FOR j=1TO i
?CHR$(64+i)" ";
NEXT j,i

```

Uses uppercase. The input is by keypress and is not echoed to the screen.

### Explanation

We loop `i` from `1` up to the limiting letter's position in the alphabet (1-based). For each `i`, we move to column `i` of the screen using `TAB`; then, `i` times, we print the `i`th letter of the alphabet followed by a space.
> 2 votes

# Answer
# Charcoal, 18 bytes

```
Ｆ⁺⌕αθ¹«Ｐ×⁺§αι ⁺ι¹↘

```

Try it online!
> 1 votes

# Answer
# Pyth, 17 bytes

```
.e+*kd*+bdhk<GhxG

```

**Try it here (pretty print version).**

---

# How does this work?

* `hxG` \- Takes the index of the input in the lowercase alphabet.
* `<G` \- Trims every character after the input from the alphabet.
* `.e` \- Enumerated Map. Maps over the trimmed alphabet with the indexes as `k` and the letters as `b`.
* `*kd` \- Append `k` spaces.
* `+bd` \- `b` \+ a space (the current letter + space).
* `*...hk` \- Repeat `k+1` times.
* `+(...)(...)` \- Concatenate.
> 1 votes

# Answer
# Braingolf, 65 bytes

```
a#a-# 7-,-~vc<!?>[$_]:$_|&,(.#a-!?.>[# M]1+>[.M# M]:$_!@|v#
&@R);

```

Try it online!

Lowercase.

Contains 1 trailing space on each line, and a trailing newline at the end of output.
> 1 votes

# Answer
# SOGL V0.12, ~~15~~ ~~14~~ 12 bytes

```
ZZ,Wm{ē@Ο}¹¾

```

Try it Here!
> 1 votes

# Answer
# Mathematica, 70 bytes

```
(T=Table)[""<>{" "~T~i,T[Alphabet[][[i]]<>" ",i]},{i,LetterNumber@#}]&

```

lowercase

outputs a list

*thanx @ngenisis for corrections*

For version place `Column@` at the beginning
> 1 votes

# Answer
# JavaScript, ~~102~~ 94 bytes

*2 bytes saved thanks to Neil*

```
f=
a=>[...Array(parseInt(a,36)-9)].map((a,b)=>''.padEnd(b).padEnd(b*3+1,(b+10).toString(36)+' '))

console.log(f('k').join`\n`)
```
> 1 votes

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

```
n=>{var i='`';var l="";for(;i<n;l+='\n'){l+="".PadLeft(i++-96);for(int s=96;s++<i;)l+=i+" ";}return l;}

```

Try it online!
> 1 votes

# Answer
# Retina, 51 bytes

```
^.
$&$&
}T`L`_L`^.
.
$.`$* $&$.`$* ¶
+`(\w) \B
$&$1

```

Try it online! Explanation:

```
^.
$&$&

```

Duplicate the (first) letter.

```
}T`L`_L`^.

```

Rotate it back 1 in the alphabet, or delete it if it's a duplicate `A`. Keep duplicating and rotating until we duplicate `A`, at which point the deletion undoes the duplication and the loop completes.

```
.
$.`$* $&$.`$* ¶

```

Replace each letter with a line with the letter padded on both sides.

```
+`(\w) \B
$&$1

```

Insert duplicate letters between all pairs of padding spaces to the right of existing letters.
> 1 votes

# Answer
# Haskell, 57 bytes

```
x!'@'=x
x!e=([e]:[' ':r++' ':[last r]|r<-x])!pred e
([]!)

```

Try it online!
> 1 votes

# Answer
# Charcoal, 15 bytes

```
Ｆ…·AＳ«Ｐ⪫Ｅ…@ιι ↘

```

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

```
 …·AＳ           Inclusive character range from A to the input
Ｆ    «          Loop over each character
         …@ι    Exclusive range from @ to the current character
        Ｅ   ι   Replace each element with the current character
       ⪫        Join with spaces
      Ｐ         Print without moving the cursor.
              ↘ Move the cursor down and right.

```

If extra padding was legal, this would work for 14 bytes:

```
Ｅ…·?θ⁺× κ⪫× κι

```

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

# Answer
# Excel VBA, 72 Bytes

Anonymous VBE immediate window function that takes input from cell `A1` and outputs to the VBE immediate window

```
For i=1To Asc([A1])-64:[B1]=i:?Space(i-1)[REPT(CHAR(B1+64)&" ",B1)]:Next

```
> 1 votes

# Answer
Very naïve approach.

# Tcl, 100 bytes

```
time {puts [format %[incr i]s \ ][string repe [format %c\  [expr $i+64]] $i]} [expr [scan $c %c]-64]

```

Try it online!

~~Tcl, 106 bytes
```
set i 0;while \$i<[scan $c %c]-64 {puts [format %$i.s \ ][string repe [format %2c [expr $i+65]] [incr i]]}

```
Try it online!
---

Below approahes do not have a leading space
Tcl, 107 bytes
```
set i 0;while \$i<[scan $c %c]-64 {puts [format %$i.s \ ][string repe [format %c [expr $i+65]]\  [incr i]]}

```
Try it online!
Tcl, 109 bytes
```
set i 0;time {puts [format %$i.s \ ][string repe [format %c [expr $i+65]]\  [incr i]]} [expr [scan $c %c]-64]

```
Try it online!
Tcl, 111 bytes
```
set i 0;time {puts [string repe \  $i][string repe [format %c [expr $i+65]]\  [incr i]]} [expr [scan $c %c]-64]

```
Try it online!
~~
> 1 votes

# Answer
# C++ (gcc), 164 bytes

```
#include<iostream>
#define f for(int i=0;i<o-'`';i++)
using namespace std;int main(){char c;cin>>c;for(char o='a';o<=c;o++){f cout<<' ';f cout<<o<<' ';cout<<'\n';}}

```

My first attempt after a long time lurking!

Ungolfed code below:

```
#include <iostream>

using namespace std;
#define f for (auto i = 0; i < output - '`'; i++)

int main()
{
  char input;

  cin >> input;

  for (char output = 'a'; output <= input; output++)
  {
    f cout << ' ';

    f cout << output << ' ';

    cout << endl;
  }
}

```

Try it online!
> 1 votes

# Answer
# brainfuck, 111 bytes

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

```

Try it online!

Surprising how the Turing Tarpit itself can out-golf some other languages.

### The breakdown:

`Section A`

```
>+[+[<]>>+<+]                                                       create character 'A'
             ,                                                      take input
              >>++++++++++                                          create '\n' character
                          >++++[>++++++++<-]                        create ' ' character
                                            ----[<<<->>>----]<<<-   map input to (1->26)

```

`Section B`

```
[<[-<+>>>>>.<<<<]+                                 print N spaces, then increment N
                  <[->+>>.>>.<<<<<]                print (N-1) of the Nth letter and spaces
                                   >>>.+>.<<-]     print additional letter, and newline

```
> 1 votes

# Answer
# \>\<\>, 85 Bytes

```
i1-&0\1o*84\      \o*84o:$\
@)?;&>:> :?/~1+:88*+$:@>:?/~ao&:
     /-/          /$1- /

```

Try it online
> 1 votes

# Answer
# Java (OpenJDK 8), 81 bytes

```
c->{String s="";for(int d=64;d++<c;)System.out.printf((s=" "+s+"%1$c ")+"%n",d);}

```

Try it online!
> 1 votes

# Answer
# Brain-Flak, 179 bytes

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

```

This is 178 bytes of code, and `+1` for the `-c` flag.

Try it online!

(Semi-)Readable version:

```
({}[((((()()()()){}){}){}){}])

{

    ((({}[()])()))

    {
        ({}<

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

        >[()])
    }{}

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

    <>{}

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

    <>

}

```

Fun fact: This will work with arbitrary characters above `Z`! Try it online!
> 1 votes

# Answer
# Bash, ~~93~~ 90 bytes

```
for c in {A..Z}
{
printf "%$[i++*3+2]s\n" "$(echo `yes $c|head -$i`)"
[ $c = $1 ]&&break
}

```

Try it online!

Takes input as, and outputs as, uppercase letters.

Still getting the hang of golfing in Bash, so I'm open to tips.
> 1 votes

# Answer
# C (GCC), 115 109 Bytes

```
f(a,n,k,s,i){if(k){for(;i<s;i++)printf(" ");for(i=0;i<s+1;i++)printf("%c ",a);puts();f(++a,++n,--k,++s,0);}}

```

## Usage

```
f(65,5,5,0,0)

```

Where the two 5's are the given K value, the rest are constants used later for recursive calls.

## Ungolfed

```
f(a,n,k,s,i){
    if(k){
        for (; i<s; i++) printf(" ");
        for (i=0; i<s+1; i++) printf("%c ",a);
        puts();
        f(++a,++n,--k,++s,0);
    }
}

```

## Output
> 1 votes

# Answer
# C (gcc), 77 bytes

```
i,j;f(c){for(j=64;i||j++<c&&printf("\n%*c ",i=j-64,j);--i&&printf("%c ",j));}

```

Try it online!

Contains unsequenced access to possibly incremented `j`, so very likely to break with a different compiler :)

fixed with identical byte count
> 1 votes

# Answer
# Alice, 31 bytes

```
/A''*?h~w0O~
\I"AxrS&..r!y"kx@/

```

Try it online!

### Explanation

Linearized and with relevant spaces included, the program is as follows:

```
I'A*rh&w.O!" x A"'x?S~.0r~yk@

I                                   take input
 'A*                                append the letter A
    r                               expand to range (e.g., if input was D, string is now DCBA)
     h&w                            split string into characters, and repeat the main loop that number of times
        .O                          output copy of top string on stack with newline
          !                         move top string (last printed row) to tape
           " x A"                   push " x A"
                 'x S               replace the occurrence of "x" with
                   ?                  the string on the tape
                     ~              swap to get next letter
                      .             copy this letter
                       0r           get entire range from that letter down to "0"
                         ~          swap again to put letter on top of stack
                          y         replace all characters in this range (effectively, all non-space characters) with the next letter
                           k        repeat (end of main loop)
                            @       exit

```
> 1 votes

# Answer
# Pyth, ~~18~~ 17 bytes

*-1 thanks to @TheIOSCoder because you are apparently allowed to surround the input in quotes*

```
j.b+*dYjd*NhYGhxG

```

Try it online!

**Explanation**

```
j.b+*dYjd*NhYGhxG    accepts a token as input, must be lowercase and in quotes

j                    joins on new line
 .b   Y   N Y        maps A (lambdas NY) over B and C in parallel
   +                 joins two strings on same line
    *    *           repeats A B times
     d  d            " " or space
       j             joins B on A
           h  h      A + 1
             G  G    lowercase alphabet
               x     returns position of B in A
                     implicit input

```
> 1 votes

# Answer
# Recursiva, 28 bytes

```
{B-Oa64"P+*' '~}J' '*}C+64}"

```

Try it online!
> 1 votes

# Answer
# PHP, 69+1 bytes

```
A<?for($c=A;$c<$argn;)echo($p=str_pad)($p("
",++$i+1),$i*3,++$c." ");

```

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

---

The `Z` case cost 4 bytes. `for($c=A;$c<=$argn;)echo($p=str_pad)($p("
",++$i),$i*3,$c++." ");` (with `-nR`) works for `A` to `Y`.

Printing a list of underscore-separated lines would save two bytes, but that´d feel like cheating.
> 1 votes

# Answer
# K (oK), 35 bytes

**Solution:**

```
`c${,/(x#32),(x+1)#,65+x,-33}'!-64+

```

Returns list of strings. prepend ``0:` to write to stdout instead.

Try it online!

**Example:**

```
`c${,/(x#32),(x+1)#,65+x,-33}'!-64+"F"
("A "
 " B B "
 "  C C C "
 "   D D D D "
 "    E E E E E "
 "     F F F F F F ")

```

**Explanation:**

Struggled to golf this down any further... K is interpretted right-to-left:

```
`c${,/(x#32),(x+1)#,65+x,-33}'!-64+ / the solution
                               -64+ / subtract 64 from input, "F"=>6 (implicit ascii)
                              !     / til, !6 => 0 1 2 3 4 5
   {                        }'      / lambda function with each input
                         -33        / negative 33
                       x,           / x concatenated, e.g. 0 -33
                    65+             / add 65, 0 -33 => 65 32 (aka "A ")
                   ,                / enlist, wraps "A " into a list ("A ")
             (x+1)#                 / take (#) x+1 instances of this list
            ,                       / concatenate with
      (x#32)                        / x instances of the number 32 (aka " ")
    ,/                              / raze, flattens this list down
`c$                                 / cast to characters

```
> 1 votes

# Answer
# C (gcc), 76 bytes

```
i,j;f(c){for(i=0;i++<c-64;puts(""))for(j=0;j<i;)printf("%*c",j++?2:i,i+64);}

```

Try it online!
> 1 votes

# Answer
# Ruby, 62 Bytes

Assumes input as a string (e.g., 'A'). Wasn't clear from the rules whether this was allowed. Will update if not.

*Lots* of room for improvement, I'm sure.

```
->n{a=[*'A'..n];a.map{|x|' '*a.index(x)+(x+' ')*-~a.index(x)}}

```
> 1 votes

# Answer
# Excel VBA, ~~78~~ 71 Bytes

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

```
For i=1To[Code(A1)-64]:?:?Spc(i-1);:For j=1To i:?Chr(i+64)" ";:Next j,i

```

-1 Byte for switching to leading newline over trailing, and condensing `Next` statements

-6 bytes for using `Spc()` over `String()`
> 1 votes

# Answer
# Pip, ~~22~~ 21 bytes

```
FxzIxLEaPsXi.YxX++iJs

```

Uses lowercase and takes input from the command line. Try it online!

### Explanation

Implicit: `a` is 1st cmdline arg; `z` is lowercase alphabet; `i` is `0`; `s` is space.

```
Fxz                      For each letter x in lowercase alphabet:
   IxLEa                  If x is less than or equal to a:
        P                  Print
         sXi               i spaces
            .Y             to which concatenate (the Y enforces precedence)
              xX++i        x repeated i times, after incrementing i
                   Js      joined on spaces

```
> 1 votes

# Answer
# SNOBOL4 (CSNOBOL4), 115 bytes

```
	U =&UCASE
	U INPUT @L
N	U POS(X) LEN(1) . R
	OUTPUT =DUPL(' ',X) DUPL(R ' ',X + 1)
	X =LT(X,L - 1) X + 1	:S(N)
END

```

Try it online!
> 1 votes

# Answer
# Swift, 133 bytes

```
func f(c:String){for i in 9..<Int(c,radix:36)!{var s=""
for _ in 9..<i{s+=" "}
for _ in 9...i{s+=String(i+1,radix:36)+" "}
print(s)}}

```

Try it online!
> 1 votes

# Answer
# Julia 0.4, 48 bytes

It should work the same in more recent versions of Julia as well.

```
x->[" "^i*"$c "^i for (i,c) in enumerate('A':x)]

```

Try it online!
> 1 votes

# Answer
# Julia 0.6, 40 bytes

```
c->[" "^i*"$('A'+i) "^-~i for i=0:c-'A']

```

Try it online!

Returns an array of strings containing the output. (Pretty printed on TIO using just `map (println, f(c))`.)

`^` applied to strings repeats the string that many times. `$()` executes its content and pastes the result into the string (here, the correct letter for the line). Finally, the space repetition and the letter repetition are concatenated with `*`.
> 1 votes

# Answer
## Burlesque - 39 bytes

```
-]'Ajr@id?i?*m{' []}zim{p^' j?*j_+}unsh

```

This is not fully golfed yet and (trivially at least the `sh` can be replaced with `Q`) but it's a first start. `m{}un` can probably be replaced by a version of map that unlines and `zim[` is a good candidate for a shortcut in the near future. The two maps can also probably be merged together into a single map.
> 1 votes

# Answer
# Kotlin, 57 bytes

```
{('A'..it).map{" ".repeat(it-'A')+"$it ".repeat(it-'@')}}

```

Try it online!
> 1 votes

# Answer
# Common Lisp, 89 bytes

```
(dotimes(m(-(char-code(read))63))(format t"~va~v@{~c ~:*~}~%"m #\  m(code-char(+ m 64))))

```

Try it online!
> 1 votes

# Answer
# SmileBASIC, ~~58~~ 57 bytes

```
INPUT E$WHILE L$<E$L=L+1L$=CHR$(L+#X)+" "?" "*L;L$*L
WEND

```
> 1 votes

# Answer
# Excel

```
=LET(x,SEQUENCE(CODE(A1)-64),REPT(" ",x-1)&REPT(CHAR(64+x),x))

```

Link to Spreadsheet
> 1 votes

# Answer
# Vyxal `rMj`, ~~16~~ 13 bytes

*Thanks to @Lyxal for -3 bytes by using Map Lambda instead of a for loop.*

```
kAḟƛ›nkAi*Ṅn꘍

```

Try it Online!

Explanation:

```
               # Implicit input
kA             # Constant 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  ḟ            # Index of input in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ’
   ƛ           # Map over range [0,index)
     nkAi      # Index of n in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    ›    *     # Multiply by n+1
          Ṅ    # Join with spaces
           n꘍  # Prepend n spaces
               # 'j' flag - Join top of stack with newlines and print

```
> 1 votes

# Answer
# Vim, 45 bytes

```
D:h<_
jjYZZPJ/<C-r>-
lDqqha
<esc>:,$s/\S/ & &
{$@qq@q

```

Uses lowercase. Try it online!

### Explanation

```
D

```

Delete the input letter (we'll use it later).

```
:h<_<cr>jjYZZ

```

Yank the lowercase alphabet from an article in the help file (see this tip).

```
PJ

```

Paste the alphabet and turn the blank line (where the input used to be) into a trailing space.

```
/<C-r>-<cr>

```

Find the input letter (pasting it into the find command from the "small deletion" register `-`).

```
lD

```

Move one character to the right and delete everything till the end of the line. We now have one line containing letters `a` through the input letter, with the cursor on the last character of the line.

```
qqh

```

Begin recording macro `q`. Try going left one character. If this fails, we've gotten all the way to `a` and we're done; the macro exits. Otherwise, the cursor is now on the second-last character of the top line.

```
a<cr><esc>

```

Insert a newline after the cursor, moving the final character of the top line to its own line.

```
:,$s/\S/ & &<cr>

```

On every line from this second line till the end of the file, substitute the first non-space character for space, itself, space, and itself again. This turns a line like `c` into  `c c`,  `d d` into  `d d d`, etc.

```
{$@q

```

Go back to the first line, then go to the end of the line and run the macro recursively.

```
q@q

```

Stop recording, and call the macro.
> 1 votes

# Answer
# Python 2, ~~101~~ 99 bytes

-2 because I forgot I could remove the parentheses in `print`

```
def f(l,a="abcdefghijklmnopqrstuvwxyz",s=0):
 for c in a[:a.index(l)+1]:print" "*s+(c+" ")*-~s;s+=1

```

Try it online!
> 1 votes

# Answer
# Ruby, 43 bytes

```
->c{i=0
(?A..c).map{" "*(i+=1)+[_1]*i*" "}}

```

Attempt This Online!
> 1 votes

# Answer
# Vyxal, 20 bytes

```
C65-›ɾ(nIn‹kAin*Ṅ+,)

```

Try it Online!

Explanation:

```
C65-›ɾ  # range from 1 to 0-25 depending on which letter is inputted
 (  # begin loop
  nI  # push n (current loop variable) spaces to the stack
   n‹kAin*Ṅ+  # which letter of the alphabet is n and push n letters
    separated by spaces
     ,  # output

```
> 1 votes

# Answer
# Röda, 53 bytes

```
f L{seq 0,ord(L)-65|[" "*_..`${chr(_1+65)} `*(_1+1)]}

```

Try it online!
> 0 votes

# Answer
# CJam, ~~22~~ ~~21~~ 20 bytes

This is the "list of lines" version. Just add an "N" before the close bracket to make it look nice. (Thanks to @Erik)

```
rc'@-{)_S*\_'@+*S*}%

```

Try it Online (nice version).
> 0 votes

# Answer
# Charcoal, 19 bytes

```
Ｆ⁻℅Ｓ⁶³«×⁺℅⁺ι⁶⁴ ιＪιι

```

Try it online! Link is to verbose version.

A bit of a different approach from the other answer, let's see if it's golfable...
> 0 votes

# Answer
# Proton, 47 bytes

```
c=>[' '*i+-~i*('%c '%(i+65))for i:0..ord(c)-64]

```

Not unlike the Python answers.

Try it online!
> 0 votes

# Answer
# , 39 bytes

```
[:(#\([' '&,1j1##)"0])i.@>:&.(65-~3&u:)

```

Try it online!
> 0 votes

# Answer
# Jelly, 19 bytes

```
ḢØAḣi¥p⁶ẋ"J$µLḶ⁶ẋ;"

```

Try it online!

Function that returns a list. Append `⁸Y` to print in separate lines. Erase the footer to show actual output instead of string representation.
> 0 votes

# Answer
# Shnap, ~~97~~ 96 bytes

*-1 byte because I remembered that the parser reads strings through newlines, so a literal newline is shorter than \n*

```
$c{n=65s=""for k:range(n,c+1){for range(n,k)s+=" "for range(n,k+1)s+=char(k)+" "s+="
"}return:s}

```

This is an anonymous function (actually, all functions in Shnap are anonymous...).

Try it online!

Alternative version that uses the fact that blocks return the last instruction's value

Ungolfed/explanation:

```
$ (c) {                  //Function with 1 parameter
    n=65                    //Value of 'A'
    s=""                    //The result
    for k:range(n,c+1) {    //Inclusive range from n to c, range(n,c,1,1) also works, as third arg is step and fourth is inclusive (bool).
                            //For loop variable is k
        for range(n,k)      //Exclusive range from n to k
            s+=" "          //Add a space
        for range(n,k+1)    //Inclusive range from n to k
            s+=char(k)+" "  //Add k and a space
        s+="\n"             //Add a newline

    }
    return:s                //Return the result
}

```

I really should implement string multiplication and eval...
> 0 votes

# Answer
## TXR Lisp, 77 bytes

```
(do mapdo(op pprinl`@{""@2}@{(take(inc @2)(gun @1))}`)(range #\A@1)(range 0))

```

Run:

```
This is the TXR Lisp interactive listener of TXR 184.
Quit with :quit or Ctrl-D on empty line. Ctrl-X ? for cheatsheet.
1> (do mapdo(op pprinl`@{""@2}@{(take(inc @2)(gun @1))}`)(range #\A@1)(range 0))
#<interpreted fun: lambda (#:arg-01-0173 . #:rest-0172)>
2> [*1 #\F]
A
 B B
  C C C
   D D D D
    E E E E E
     F F F F F F

```
> 0 votes

# Answer
# Pyth, 26 bytes

Should meet OPs specs.

```
VhxrG1w++*dNr@GN1*+dr@GN1N

```

Try it online!
> 0 votes

# Answer
# C++ (gcc), 179 bytes

Well, someone ought to post the most un-original method, I might as well be that someone.

```
#include <iostream>
using namespace std;
int main(){char n;cin>>n;for(char i='A';i<=n;i++){for(char k='A';k<i;k++){cout<<" ";}for(int j=0;j<=i-'A';j++){cout<<i<<" ";}cout<<endl;}}

```

An easier-to-read version of the code:

```
#include <iostream>
using namespace std;
int main()
{
    char n;
    cin>>n;
    for (char i='A';i<=n;i++)
    {
        for (int k=0;k<n-i;k++)
        {
            cout<<" ";
        }
        for (int j=0; j<n-'A'+1;j++)
        {
            cout<<i<<" ";
        }
        cout<<endl;
    }
}

```

Try it online!
> 0 votes

# Answer
# Java, 363 bytes

```
public class MyClass {
    public static void main(String args[]) {
        char x='A';
        int count=0;
      for(x='A';x<='Z';x++){
        for(int x1=count;x1>0;x1--) {
            System.out.print(" ");
        }
        for(int y=count;y>=1;y--) {
            System.out.print(x);
        }
        System.out.print(x+"\n");
       count++;
    }
    }
}

```
> 0 votes

---
Tags: code-golf, string, ascii-art, alphabet
---


title: Circumference of an ellipse

text:
# Question
Title: Circumference of an ellipse
## Challenge

Unlike the circumference of a circle (which is as simple as \\$2\pi r\\$), the circumference (arc length) of an ellipse is hard.

Given the semi-major axis \\$a\\$ and semi-minor axis \\$b\\$ of an ellipse (see the image below, from Wikipedia), calculate its circumference.

By definition, you can assume \\$0 \< b \le a\\$ for input values. The output value must be within \\$10^{-6}\\$ relative error from the expected answer for the given test cases.

Standard rules apply. The shortest code in bytes wins.

## Formulas

Relevant information can be found on Wikipedia and MathWorld. \\$C\\$ is the value of the circumference; \\$e\\$ and \\$h\\$ are helper values. The last two are Ramanujan's approximations, the first of which (the crossed-out one) does not meet the error requirements. The second approximation formula (Equation 5) barely does (verification) for up to \\$a=5b\\$ (which is also the upper limit of the test cases, so you can use it for your answer).

$$ \require{enclose} \\ \begin{align} e &= \sqrt{1-\frac{b^2}{a^2}} \\ C &= 4aE(e) = 4a\int^{\pi/2}\_{0}{\sqrt{1-e^2 \sin^2 \theta} \\;d\theta} \tag{1} \\ C &= 2 \pi a \left(1-\sum^{\infty}\_{n=1}{\left(\frac{(2n-1)!!}{(2n)!!}\right)^2 \frac{e^{2n}}{2n-1}}\right) \tag{2} \\ h &= \frac{(a-b)^2}{(a+b)^2} \\ C &= \pi (a + b) \left( 1 + \sum^{\infty}\_{n=1} { \left( \frac{(2n-1)!!}{2^n n!} \right)^2 \frac{h^n}{(2n-1)^2} } \right) \tag{3} \\ C &= \pi (a + b) \sum^{\infty}\_{n=0} { \binom{1/2}{n}^2 h^n } \tag{4} \\ \enclose{horizontalstrike}{C} &\enclose{horizontalstrike}{\approx \pi \left( 3(a+b) - \sqrt{(3a+b)(a+3b)} \right)} \\ C &\approx \pi (a+b) \left( 1+ \frac{3h}{10 + \sqrt{4-3h}} \right) \tag{5} \end{align} $$

## Test cases

All the values for C (circumference) are calculated using Equation 4 with 1000 terms, and presented with 10 significant figures.

```
a     b     C
1     1     6.283185307
1.2   1     6.925791195
1.5   1     7.932719795
2     1     9.688448220
3     1     13.36489322
5     1     21.01004454
20    10    96.88448220
123   45    556.6359936

```

# Answer
> 18 votes
# Wolfram Language (Mathematica), 20 bytes

```
Perimeter[#~Disk~#]&

```

Try it online!

-2 bytes from @Roman (see comments)

# Answer
> 15 votes
# Python 3, ~~68~~ 67 bytes

```
f=lambda a,b,k=2:k>>9or(1-b*b/a/a)*(k-4+3/k)/k*f(a,b,k+2)+6.28319*a

```

Try it online!

An exact infinite series, given sufficiently accurate values of \\$2\pi \approx 6.28319\\$ and \\$\infty \approx 9\\$.

### ~~69~~ 68 bytes

```
f=lambda a,b,k=0:k//7*.785398*a*(8-k)or f(a+b,2*(a*b)**.5,k*b/a/2+4)

```

Try it online!

Another exact series, given sufficiently accurate values of \\$\frac\pi4 \approx .785398\\$ and \\$8 \approx 7\\$. This one converges extremely quickly, using just five recursive calls for each test case! The recursion exactly preserves the invariant value

$$\left(1 + \frac{kb}{8a}\right)C(a, b) - \frac{kb}{8a}C(a + b, 2\sqrt{a b}),$$

which can then be approximated as \\$(1 - \frac k8)2\pi a\\$ when \\$a, b\\$ become sufficiently close.

# Answer
> 10 votes
# , ~~60~~ 57 bytes

```
function(a,b,c=a+b,h=3*(a-b)^2/c)pi*(c+h/(10+(4-h/c)^.5))

```

Try it online!

Straightforward implementation of Ramanujan's 2nd approximation (eq 5).

Rather sadly, this approximation comes out as ~~much~~ more concise than a more-interesting **different approach** prompted by the comments: 'draw' a big ellipse, and measure around the edge of it (unfortunately counting the actual pixels wasn't going to work...):

**, ~~90~~ ~~65~~ 62 bytes**

*Edit: -3 bytes by calculating hypotenuse length using `abs` value of complex number*

```
function(a,b,n=1e5)sum(4*abs(diff(b*(1-(0:n/n)^2)^.5)+1i*a/n))

```

Try it online!

**How?** (ungolfed code):

```
circumference_of_ellipse=
function(a,b                # a,b = axes of ellipse
n=1e6){                     # n = number of pixels to 'draw' across 'a' axis
x=a*0:n/n                   # x coordinates = n pixels from 0 to a
y=b*(1-(x/a)^2)^.5)         # y coordinates = to satisfy (x/a)^2 + (y/b)^2 =1
                            # we could actually draw the (quarter) ellipse here
                            # with 'plot(x,y)'
step_y=diff(y)              # step_y = change in y for each step of x
step_x=a/n                  # step_x = size of each step of x
h=(step_y^2+step_x^2)^.5    # h=hypotenuse of triangle formed by step_y & step_x
sum(4*h)                    # sum all the hypotenuses and multiply by 4
                            # (since we only 'drew' a quarter of the ellipse)

```

# Answer
> 8 votes
# APL (Dyalog Unicode), ~~28~~ ~~25~~ 23 bytes

Thanks to Bubbler for -5 bytes!

Assumes `⎕IO←0`.

```
f←○1⊥+×9(×⍨*×.5!⍨⊢)∘⍳⍨-÷+

```

Try it online!

This calculates

$$ \pi \cdot \sum\_{n=0}^{8} (a+b) \cdot \left( h^{\prime n} \binom{1/2}{n} \right) ^2 \qquad h^\prime = {{a-b}\over{a+b}} $$

which is a good enough approximation using the 4th formula. For the explanation the function will be split into two. `f` is the main function and `g` calculates \\$ \left( \alpha^{\prime n} \binom{1/2}{n} \right) ^2 \\$ for \\$n\\$ from \\$0\\$ to \\$\omega-1\\$:

```
g ← (×⍨*×.5!⍨⊢)∘⍳
f ← ○1⊥+×9g⍨-÷+

```

Starting with `a f b` from the right:

`-÷+` calculates \\$h^\prime = (a-b)÷(a+b)\\$.
`g⍨` is `g` commuted =\> `9 g⍨ h' ≡ h' g 9`. `g` returns a vector of the 9 values of \\$\left( h^{\prime n} \binom{1/2}{n} \right) ^2\\$.
multiplies \\$a + b\\$ to this vector.
`1⊥` converts the resulting vector from base 1, which is the same as summing the vector.
multiplies the resulting number by \\$\pi\\$.

Now to `h' g 9`:

is an index generator, with `⎕IO←0`, `⍳9` results in the vector `0 1 ... 8`.
The remaining train `×⍨*×.5!⍨⊢` is now called with \\$h^\prime\\$ as a left argument and the vector \\$v = (0,1, \cdots, 8)\\$ as a right argument:

`.5!⍨⊢` is the commuted binomial coefficient called with the vector `v` on its right and \\$0.5\\$ on its left. This calculates \\$\binom{1/2}{n}\\$ for all \\$n \in v\\$.
multiplies this vector element-wise with \\$h^\prime * n\\$ (\\$\*\\$ denotes exponentiation).
`×⍨` is commuted multiplication, which given only a right argument, seems to use this as left and right argument? and squares the vector element-wise.

# Answer
> 7 votes
# Ruby, 63 bytes

```
->a,b,h=1r*(a-b)/a+=b{3.141593*a*((154+53*h*=h)*h*h/1e4+h/4+1)}

```

Try it online!

A direct port of @Arnauld's JavaScript answer is shorter (58 bytes). However, I like the 63-byter above because it differs from other approaches in that it's a cubic polynomial: no square roots, no infinite series.

This excellent review lists nearly 40 different methods for approximating the circumference of an ellipse, with graphs of the relative error in each approximation as a function of \\$b/a\\$. Inspection of the graphs shows that only a few of the listed methods are capable of satisfying the required tolerance of \\$10^{-6}\\$ for all test cases. Since several answers here had already explored 'Ramanujan II' (eq. (5)), I decided to look at the Padé approximations 'Padé 3/2' and 'Padé 3/3'.

A Padé approximant is a rational function with coefficients chosen so as to match the largest possible number of terms in a known power series. In this case, the relevant power series is the infinite sum that appears in eq. (4). The Padé 3/2 and Padé 3/3 approximants for this series are mathematically straightforward (see the review linked above) but not suited to code golf. Instead, an *approximation to the approximants* is obtained by least-squares fitting. The resulting cubic polynomial (with truncated coefficients), as implemented in the code, is $$ 0.0053h^3 + 0.0154h^2+0.25h+1. $$ Note that this function is overfitted to the test cases, partly because of the truncation and partly because the fit was optimised using only those values of \\$h=(a-b)^2/(a+b)^2\\$ that occur in the test cases. (Consequently, `Math::PI` cannot be substituted in place of `3.141593`, despite having the same byte count, without yielding relative errors above the \\$10^{-6}\\$ threshold for the two test cases for which \\$b/a=1/2\\$.)

# Answer
> 7 votes
# x87 machine code, ~~65~~ ~~59~~ 53 bytes

```
00000000: d9c1 d9c1 dec1 d9ca dee9 d8c8 d9c1 d8c8  ................
00000010: def9 6a03 8bf4 de0c ff04 df04 d9c1 dee9  ..j.............
00000020: d9fa 8304 06de 04de f9d9 e8de c1d9 ebde  ................
00000030: c9de c95e c3                             ...^.

```

Listing:

```
D9 C1       FLD   ST(1)             ; load a to ST
D9 C1       FLD   ST(1)             ; load b to ST
DE C1       FADD                    ; a + b
D9 CA       FXCH  ST(2)             ; save result for end
DE E9       FSUB                    ; a - b
D8 C8       FMUL  ST(0), ST(0)      ; ST ^ 2
D9 C1       FLD   ST(1)             ; copy a + b result to ST
D8 C8       FMUL  ST(0), ST(0)      ; ST ^ 2
DE F9       FDIV                    ; calculate h
6A 03       PUSH  3                 ; load const 3
8B F4       MOV   SI, SP            ; SI to top of CPU stack
DE 0C       FIMUL WORD PTR[SI]      ; ST = h * 3
FF 04       INC   WORD PTR[SI]      ; 4 = 3 + 1
DF 04       FILD  WORD PTR[SI]      ; load const 4
D9 C1       FLD   ST(1)             ; load 3h to ST
DE E9       FSUB                    ; 4 - 3h
D9 FA       FSQRT                   ; sqrt(ST)
83 04 06    ADD   WORD PTR[SI], 6   ; 10 = 4 + 6
DE 04       FIADD WORD PTR[SI]      ; ST + 10
DE F9       FDIV                    ; 3h / ST
D9 E8       FLD1                    ; load const 1
DE C1       FADD                    ; ST + 1
D9 EB       FLDPI                   ; load PI
DE C9       FMUL                    ; * PI
DE C9       FMUL                    ; * ( a + b ) from earlier
5E          POP   SI                ; restore CPU stack
C3          RET                     ; return to caller

```

Callable function, input `a` and `b` in `ST(0)` and `ST(1)`. Output in `ST(0)`. Implements Ramanujan's 2nd approximation (eq 5) in full hardware 80-bit extended precision.

Test program:

# Answer
> 6 votes
# JavaScript (ES7),  ~~59~~  56 bytes

*Saved 2 bytes thanks to @DominicvanEssen*

```
a=>b=>Math.PI*((h=3*(a-b)**2/(a+=b))/(10+(4-h/a)**.5)+a)

```

Try it online!

# Answer
> 4 votes
# C (gcc), ~~97~~ ~~92~~ 91 bytes

Saved ~~4~~ 5 bytes thanks to Dominic van Essen!!!
Saved 2 bytes thanks to ceilingcat!!!

```
float f(a,b,k)float a,b,k;{k=k?:2;k=k>999?1:(1-b*b/a/a)*(k-4+3/k)/k*f(a,b,k+2)+6.283185*a;}

```

Try it online!

Port of Anders Kaseorg's Python answer.

# Answer
> 4 votes
# , ~~31~~ 30 bytes

-1 byte thanks to Jonah!

```
[:o.1#.+*i.@9*:@(^~*0.5!~[)-%+

```

Try it online!

Essentially a J port of @ovs's APL solution.

# Answer
> 3 votes
# MathGolf, 20 bytes

```
-ëΣ_¬/²3*_4,√♂+/)π**

```

Port of my 05AB1E answer, and thus also implements a modification of the fifth formula.

Try it online.

**Explanation:**

```
-                     # b-a
 ëΣ                   # a+b
   _                  # Duplicate
    ¬                 # Rotate stack: b-a,a+b,a+b → a+b,b-a,a+b
     /                # Divide
      ²               # Square
       3*             # Multiply by 3
         _            # Duplicate
          4,          # Subtract from 4
            √         # Square-root
             ♂+       # Add 10
               /      # Divide
                )     # Increment by 1
                 π*   # Multiply by PI
                   *  # Multiply by the a+b we've duplicated
                      # (after which the entire stack is output implicitly as result)

```

# Answer
> 3 votes
# Wolfram Language (Mathematica), ~~25~~ 24 bytes

```
4EllipticE[1-(#2/#)^2]#&

```

Try it online!

-1 thanks to @AndersKaseorg

Note that Mathematica uses a different convention for elliptic integrals, hence the square root disappears.

# Answer
> 3 votes
# Haskell, 73 bytes

```
e a b=(a+b)*pi*(1+3*l/(10+sqrt(4-3*l))+3*l^5/2^17)where l=((a-b)/(a+b))^2

```

Experimenting with an improved version of (5):

$$E(a,b) = \pi (a+b) \left( 1 + \frac{3h^2}{10 + \sqrt{4-3h^2}} + \frac{3h^{10}}{2^{17}}\right)$$

# Answer
> 3 votes
# MATL, 19 bytes

```
y/U_Q.5t_hlbZh*YPE*

```

Try it online! Or verify all test cases.

### Formula used

This is based on formula (1) from the challenge description, \\\[ C = 4a\int^{\pi/2}\_{0}{\sqrt{1-e^2 \sin^2 \theta} ;d\theta} = 4 a\\,E(e), \\\] where \\$e\\$ is the eccentricity, \\\[ e = \sqrt{1 - b^2/a^2}, \\\] and \\$E\\$ is the complete elliptic integral of the second kind. This integral can be expressed in terms of Gauss' hypergeometric function, \\${}\_2F\_1\\$, as follows: \\\[ E(e) = \tfrac{\pi}{2} \\;{}\_2F\_1 \left(\tfrac12, -\tfrac12; 1; e^2 \right). \\\] Combining the above gives the formula used in the code: \\\[ C = 2\pi a \\;{}\_2F\_1 \left(\tfrac12, -\tfrac12; 1; 1 - b^2/a^2 \right). \\\]

### Code explanation

```
y       % Implicit inputs: a, b. Duplicate from below
        % STACK: a, b, a
/       % Divide
        % STACK: a, b/a
U_Q     % Square, negate, add 1
        % STACK: a, 1-(b/a)^2
.5t_h   % Push 0.5, duplicate, negate, concatenate
        % STACK: a, 1-(b/a)^2, [0.5, -0.5]
1       % Push 1
        % STACK: a, 1-(b/a)^2, [0.5, -0.5], 1
b       % Bubble up in the stack
        % STACK: a, [0.5, -0.5], 1, 1-(b/a)^2
Zh      % Hypergeometric function, 2F1
        % STACK: a, 2F1([0.5, -0.5], 1, 1-(b/a)^2)
*       % Multiply
        % STACK: a * 2F1([0.5, -0.5], 1, 1-(b/a)^2)
YPE     % Push pi, multiply by 2
        % STACK: a * 2F1([0.5, -0.5], 1, 1-(b/a)^2), 2*pi
*       % Multiply. Implicit display
        % STACK: 2*pi*a * 2F1([0.5, -0.5], 1, 1-(b/a)^2)

```

# Answer
> 3 votes
# APL(NARS), 21 chars

```
a←⎕⋄{√+/×⍨a×1 2○⍵}∫○2

```

test:

```
      a←⎕⋄{√+/×⍨a×1 2○⍵}∫○2
⎕:
      1 1
6.283185307
      a←⎕⋄{√+/×⍨a×1 2○⍵}∫○2
⎕:
      123 45
556.6359936

```

it is based on the parametric representation of ellipse something as

`phi(t)=(a cos(t),b sin(t)) t∊[0,2π)` and the formula for find the lenght of the curve $$L(\varphi)=\int\_0^{2\pi} \left| \varphi'(t) \right|dt $$

where `phi'(t)=(a -sin(t), b cos(t) ) t∊[0,2π)`.

It is possible calculate more digit in that integral but solution is more long, as in

```
      ⎕FPC←3000⋄a←⎕⋄300⍕{√+/×⍨a×1 2○⍵}∫○2v
⎕:
      1 1
 6.283185307179586476925286766559005768394338798750211641949889184615632812572417997256069650684234135964296173026564613
      294187689219101164463450718816256962234900568205403877042211119289245897909860763928857621951331866892256951296467
      573566330542403818291297133846920697220908653296426787214520498282547
      300⍕○2v
 6.283185307179586476925286766559005768394338798750211641949889184615632812572417997256069650684234135964296173026564613
      294187689219101164463450718816256962234900568205403877042211119289245897909860763928857621951331866892256951296467
      573566330542403818291297133846920697220908653296426787214520498282547

```

# Answer
> 2 votes
# SageMath, 37 bytes

```
lambda a,b:4*a*elliptic_ec(1-b*b/a/a)

```

Try it online!

Uses the elliptic integral formulation.

# Answer
> 2 votes
# 05AB1E, ~~22~~ ~~21~~ 20 bytes

```
ÆnIOn/3*D4s-tT+/>IOžqP

```

Implements the fifth formula. Input as a pair \\$\[a,b\]\\$.

-1 byte thanks to *@ovs*.

Try it online or verify all test cases.

**Explanation:**

```
Æ                     # Reduce the (implicit) input-pair by subtraction: a-b
 IO                   # Push the input-pair again and sum it: a+b
   /                  # Divide them by one another: (a-b)/(a+b)
    n                 # Square it: ((a-b)/(a+b))²
     3*               # Multiply it by 3: ((a-b)/(a+b))²*3
       D              # Duplicate that
        4α            # Take the absolute difference with 4: |((a-b)/(a+b))²*3-4|
          t           # Take the square-root of that: sqrt(|((a-b)/(a+b))²*3-4|)
           T+         # Add 10: sqrt(|((a-b)/(a+b))²*3-4|)+10
             /        # Divide the duplicate by this:
                      #  (a-b)²/(a+b)²*3/(sqrt(|((a-b)/(a+b))²*3-4|)+10)
              >       # Increase it by 1:
                      #  (a-b)²/(a+b)²*3/(sqrt(|((a-b)/(a+b))²*3-4|)+10)+1
               IO     # Push the input-sum again: a+b
                 žq   # Push PI: 3.141592653589793
                   P  # Take the product of the three values on the stack:
                      #  ((a-b)²/(a+b)²*3/(sqrt(|((a-b)/(a+b))²*3-4|)+10)+1)*(a+b)*π
                      # (after which the result is output implicitly)

```

Note that I use \\$\left|3h-4\right|\\$ instead of \\$4-3h\\$ in my formula to save a byte, but given the constraints \\$0\<b\leq a\\$, \\$h\\$ will be: \\$0\leq h\<1\\$, and thus \\$3h\\$ will be at most \\$2.999\dots\\$.
I also use \\$h=\left(\frac{a-b}{a+b}\right)^2\\$ instead of \\$h=\frac{(a-b)^2}{(a+b)^2}\\$ to save another byte (thanks to *@ovs*).

# Answer
> 2 votes
# APL (Dyalog Extended), ~~28~~ 26 bytes

```
○+×1+∘(⊢÷10+∘√4-⊢)3×2*⍨-÷+

```

Try it online!

ovs's conversion to a train.

-2 using .

# APL (Dyalog Extended), 35 bytes

```
{h←3×2*⍨⍺(-÷+)⍵⋄(○⍺+⍵)×1+h÷10+√4-h}

```

Try it online!

Uses Equation 4.

Longer than the other APL answer because there's more than one usage of \\$h\\$.

# Answer
> 2 votes
# Charcoal, 52 bytes

```
≧×χφＮθＮηＩ×⁴ΣＥＥφＥ²∕⁺ιλφ₂⁺××θθ⁻Σι⊗₂Πι××ηη⁻⁻²Σι⊗₂⁻⊕ΠιΣι

```

Try it online! Link is to verbose version of code. Works by approximating the line integral for a quadrant. The default precision is unfortunately only ~5 significant figures so the first four bytes are needed to increase the precision to ~7 significant figures. Further increases are possible for the same byte count but then it becomes too slow to demonstrate on TIO. Explanation:

```
≧×χφ

```

Increase the number of pieces \\$ n \\$ in which to divide the quadrant from \\$ 1,000 \\$ to \\$ 10,000 \\$. `≧×φφ` would increase it to \\$ 1,000,000 \\$ but that's too slow for TIO.

```
ＮθＮη

```

Input the ellipse's axes \\$ a \\$ and \\$ b \\$.

```
Ｉ×⁴Σ

```

After calculating the approximate arc length of each piece into which the quadrant was subdivided, take the sum, multiply by \\$ 4 \\$ for the whole ellipse and output the result.

```
ＥＥφＥ²∕⁺ιλφ

```

Create a list of pieces of the quadrant. In the ellipse equation \\$ \left ( \frac x a \right ) ^ 2 + \left ( \frac y b \right ) ^ 2 = 1 \\$ we can set \\$ \left ( \frac {x\_i} a \right ) ^ 2 = \frac i n \\$ and \\$ \left ( \frac {y\_i} b \right ) ^ 2 = 1 - \frac i n \\$. Given a piece index \\$ i \\$ we want to calculate the distance between \\$ ( x\_i, y\_i ) \\$ and \\$ ( x \_{i+1}, y\_{i+1} ) \\$. For each \\$ i \\$ we calculate \\$ j = \frac i n \\$ and \\$ k = \frac {i+1} n \\$ and loop over the list.

```
₂⁺××θθ⁻Σι⊗₂Πι××ηη⁻⁻²Σι⊗₂⁻⊕ΠιΣι

```

The distance \\$ \sqrt { ( a \sqrt k - a \sqrt j ) ^ 2 + ( b \sqrt { 1 - j } - b \sqrt { 1 - k } ) ^ 2 } \\$ expands to \\$ \sqrt { a^2 \left ( j + k - 2 \sqrt { j k } \right ) + b^2 \left ( (1 - j) + (1 - k) - 2 \sqrt { (1 - j) (1 - k) } \right ) } \\$ which expands to \\$ \sqrt { a^2 \left ( j + k - 2 \sqrt { j k } \right ) + b^2 \left ( 2 - (j + k) - 2 \sqrt { 1 + j k - (j + k) } \right ) } \\$.

# Answer
> 1 votes
# Symja, 35 bytes

```
f=N(4*#1*EllipticE(1-#2*#2/#1/#1))&

```

Try It Online!

A port of the SageMath answer in Symja.

# Answer
> 1 votes
# Japt, 35 bytes

```
MP*ºH=3*(U-V ²/(U±V)/(A+(4-H/U ¬ +U

```

Try it

# Answer
> 1 votes
# Jelly, 20 bytes

```
I÷S²3×÷ạ4½+⁵Ʋ$‘×S×ØP

```

A monadic Link accepting a pair of `[a, b]` which yields the result of formula 5.

**Try it online!**

---

I thought formula 4 would be the way to go, but only got 21:

```
9Ḷ.c×⁹I÷S*⁸¤²ʋ€×ØP×SS

```

Try it online!

# Answer
> 1 votes
# Pyth, 40 bytes

```
A,hQeQJc^-GH2^+GH2**.n0+GHhc*3J+T@-4*3J2

```

Try it online!

Just formula 5, like most other answers here.

# Answer
> 1 votes
# Perl 5, 70 bytes

```
sub{my$s;map$s+=sqrt+($_[0]*cos)**2+($_[1]*sin)**2,0..1570795;4e-6*$s}

```

Try it online!

# Perl 5, 78 bytes

```
sub f{($a,$b)=@_;$H=3*(($a-$b)/($a+=$b))**2;3.141593*$a*(1+$H/(10+sqrt 4-$H))}

```

With the `a+=b` trick stolen from the Javascript answer.

Try it online!

Or this one which is 13 bytes less (but uses core module List::Util)

# Perl 5 -MList::Util=sum, ~~74~~ ~~65~~ 65+16 bytes

```
sub f{4e-6*sum map sqrt+($_[0]*cos)**2+($_[1]*sin)**2,0..1570795}

```

Try it online!

Which numerically calculates a variant of formula (1).

I was surprised this worked with sin and cos of integers up to 1570795 ≈ 500000π. But the tests in the question in "Try it online" has relative error \< 0.000001. Guess `sin²(the integers)` is "averaged out" good enough.

# Answer
> 1 votes
# CJam, 29 bytes

```
{_:+_P*@:-@d/_*3*_4\-mqA+/)*}

```

Try it online!

# Answer
> 1 votes
# PARI/GP, 31 bytes

```
f(a,b)=4*a*ellE((1-b^2/a^2)^.5)

```

Attempt This Online!

# Answer
> 1 votes
# Python/mpmath, 51 bytes

```
lambda a,b:8*elliprg(0,a*a,b*b)
from mpmath import*

```

Attempt This Online!

Using Carlson's symmetric integrals – as seen here – not only removes the need to sort input, it saves 1 byte off the bog-standard \\$4aE(e)\\$ formula. As given in DLMF 19.30.5, \\$L=8R\_G(0,a^2,b^2)\\$.

# Answer
> 0 votes
# Arn, 22 bytes

```
┴þ5‡Ôç¸„”R¤ËíÜç›WðÙÝÁ*

```

Try it! A pretty good approximation, but not exact for the larger values. Uses the crossed out formula (which I assume was removed due to the innacuracy). For any wondering, I managed to get the non-crossed out formula 5 to 33 bytes, but I couldn't figure out how to shorten it (and it was even less accurate than this one).

# Explained

Unpacked: `pi*(3*(+\)-:/(*3+:})*+3*:}`

```
pi                     Variable; first 20 digits of π
  *
    (
          3
        *
          (+\)         Folded sum ([a, b] -> a + b)
      -
        :/             Square root
            (
                  _    Variable; initialized to STDIN; implied
                *
                  3
              +
                  _    Implied
                :}     Tail
            )
          *
              _        Implied
            +
                3
              *
                  _    Implied
                :}
                       Ending parentheses implied

```

---
Tags: code-golf, math, geometry
---