title: Generate Sexy Primes

text:
# Question
Title: Generate Sexy Primes
Sexy Primes are pairs of numbers \\$(n, n+6)\\$ such as \\$n\\$ and \\$n+6\\$ are both prime

You need to create a function which will take an integer, check for sexy primes from 0 to that integer, and return an array of arrays.

For example, `listSexy(30)` must return `[[5,11], [7,13], [11,17], [13,19], [17,23], [23,29]]` or some equivalent.

This is so the program with the shortest bytecount wins!

# Answer
# MATLAB 32

```
i=1:n;i(isprime(i)&isprime(i+6))

```

n is your number
> 13 votes

# Answer
## J, 34 33 31 32 39 37 characters

```
s=.[:(,.-&6)[:I.1([:*/p:)"1 i.,.6-~i.

```

Lost a character keeping both primes below the limit...and another 7 declaring a function.

Usage:

```
   s 100
11  5
13  7
17 11
19 13
23 17
29 23
37 31
43 37
47 41
53 47
59 53
67 61
73 67
79 73
89 83

```

**Edit**

Seems like a lot of the new answers are not creating functions, taking input or limiting both numbers in the pair to be below `n` \- if I ignore those restrictions too I can get down to **28 characters**:

```
(,.6&+)I.*/"1[1 p:(i.,.6+i.)

```
> 6 votes

# Answer
## *Mathematica*, 35

```
{#,#+6}&~Array~#~Cases~{__?PrimeQ}&

```
> 6 votes

# Answer
### GolfScript, 32 characters

```
~),2>{:P{(.P\%}do(!},:L{6+L?)},p

```

Since the output format was not specified, the code above will print the lower prime of each pair. Thus a number `x` is included if `x` and `x+6` are both prime and both are below `n`. Input is given as single number on STDIN.

```
> 150
[5 7 11 13 17 23 31 37 41 47 53 61 67 73 83 97 101 103 107 131]

```
> 4 votes

# Answer
# Python 2, 137 132 126 122 118

```
f=lambda x:not[y for y in range(2,x)if x%y==0]
i=30
print [(x,y)for x in range(i)for y in range(i)if f(x)&f(y)&x-6==y]

```

Try it online!

Using list comprehensions, as well as the fact that `[] = False`

`f(x)` actually returns all the factors of `x`, and you can then work out prime-ness from that.
> 4 votes

# Answer
## Python (~~93 90 99~~ 95)

Yay for quick and dirty `isprime` functions!

```
a=lambda x:all(x%i for i in range(2,x));b=2
while b<input():
 b+=1
 if a(b)&a(b+6):print b,b+6

```
> 3 votes

# Answer
# K3 / Kona, 45

```
{a@&6=(-).'a:,/a,\:/:a:&{(x>1)&&/x!'2_!x}'!x}

```

.

```
{a@&6=(-).'a:,/a,\:/:a:&{(x>1)&&/x!'2_!x}'!x}100
(11 5
 13 7
 17 11
 19 13
 23 17
 29 23
 37 31
 43 37
 47 41
 53 47
 59 53
 67 61
 73 67
 79 73
 89 83)

```

And the same solution in the current incarnation of K which is identical to the K3 solution except for the fact that it does not have an inbuilt mod operator, which adds about 14 chars for 59

```
{a@&6=(-).'a:,/a,\:/:a:&{(x>1)&&/{x-y*x div y}[x;2_!x]}'!x}

```
> 3 votes

# Answer
## C, 102 99 95 chars

Returning an array in C is something you try to avoid. So the function `s` gets the limit `n` and a pointer to an array of integers, and fills it with the data. Each pair of sexy primes is placed in two positions in the array. So `o[0]=5`, `o[1]=11`, `o[2]=7`, `o[3]=13`. The function assumes the array is large enough.

```
x=7,l;
p(){
    return++l>=x/2||x*(x-6)%l&&p();
}
s(int n,int*o){
    for(;l=++x<=n;)p()?*o++=x-6,*o++=x:0;
}

```
> 3 votes

# Answer
## x86-Assembly (78 Bytes)

This example uses Intel syntax. Besides, here the `fastcall` or `register` calling convention is used (the latter from 32-bit Delphi), so the parameter is in `ecx`. I also introduce a second parameter that points to a free space for the result and is saved in `edx`. A function for allocating memory space would be specific to the operating system and a transfer via the stack would be problematic, so I chose this option.

```
listSexy:
   mov   ebp, esp      ; 89E5    Save initial esp
   mov   edi, edx      ; 89D7    Save second parameter in edx

   ; Part One: Save all prime numbers from 3 to the limit on the stack
   ; (This takes 32 Bytes)
   xor   eax, eax      ; 31C0    set eax = 1 (shorter than mov eax, 1)
   inc   eax           ; 40
checkComplete:
   add   eax, 2        ; 83C002  Go to next possible number (first is 3)
   cmp   eax, ecx      ; 39C8    Has the limit, i.e. the parameter, been skipped?
   jae   partTwo       ; 7316
   mov   ebx, esp      ; 89E3    Check it against all previous prime numbers
checkNext:             ;         which are stored between ebp and esp
   cdq                 ; 99      Clear edx for the later division
   push  eax           ; 50      Put the number on the stack
   cmp   ebx, ebp      ; 39E5    Has the check already completed?
   je    partTwo       ; 74F1    The comfirmed prime number remains on stack
   mov   esi, [ebx]    ; 8B33    Load a previous prime
   div   esi           ; F7F6
   pop   eax           ; 58
   test  edx, edx      ; 85D2    Is esi a divider?
   je    checkComplete ; 74E8
   add   ebx, 4        ; 83C304  Let ebx point to the next possible divisor
   jmp   checkNext     ; EBEC

   ; Part Zwo: Check all prime numbers if they are sexy primes
   ; (This takes 39 Bytes)
partTwo:
   mov   ebx, ebp      ; 89E5    Start with the first prime number, i.e. 3
NextPrime:
   sub   ebx, 4        ; 83EB04  Let ebx point to the next prime number
   cmp   ebx, esp      ; 39E3    Has the last number been reached? It cant be sexy,
                       ;         since it has no successors here
   jmp   Finished      ; 761E
   mov   edx, ebx      ; 89DA    Check all successors up to a distance of 6
   mov   eax, [ebx]    ; 8B03    eax is the prime number whose successors are checked
   add   eax, 6        ; 83C006
GoFurther:
   sub   edx, 4        ; 83EA04
   cmp   eax, [edx]    ; 8B02
   jb    NextPrime     ; 72EB    If the successor is too large, x can no longer be sexy
   ja    GoFurther     ; 77F7    If the successor is too small, take the next one
   mov   eax, [ebx]    ; 8B03    Load eax again (shorter than sub eax, 6)
   mov   ecx, [edx]    ; 8B0A    Load the successor which makes eax a sexy prime
   mov   [edi], eax    ; 8907    Store both in their intended place
   mov   [edi+4], ecx  ; 894F04
   add   edi, 8        ; 83C708
   jmp   NextPrime     ; EBDB

Finished:
   mov   esp, ebp      ; 89EC    Restore stack
   ret                 ; C3

```

The opcodes (and thus the size of the instruction) are given in the comment. The function can be called from C with, for example

```
int n = 100;
int resultList[50] = { };
listSexy(n, resultList);

```

The result list should be initialized with zero, since no final null byte sequence or similar is written into.

Online working example: http://tpcg.io/mEPb1Wy9
> 3 votes

# Answer
# 05AB1E, 7 bytes

```
ÅPãʒÆ7+

```

Try it online or verify a few more test cases.

**Explanation:**

```
ÅP       # Push a list of primes smaller than or equal to the (implicit) input-integer
  ã      # Create all possible pairs by taking the cartesian product with itself
         # (which will include inverted duplicates - i.e. both [5,11] and [11,5])
   ʒ     # Filter this list of pairs [a,b] by:
    Æ    #  Reduce it by subtracting: a-b
     7+  #  Add 7
         #  (only 1 is truthy in 05AB1E, so this will keep pairs that satisfy a-b+7==1)
         # (after which the resulting list of pairs is output implicitly)

```
> 3 votes

# Answer
# Brachylog, 12 10 bytes

*-2 thanks to @Fatalize*

```
≥Iṗ-₆ṗ;I≜ᶠ

```

Try it online!

### How it works

```
≥Iṗ-₆ṗ;I≜ᶠ
         ᶠ find all …
        ≜   force number-finding of constraints that fulfill …
             (strictly not necessary, but otherwise constraints will be returned)
≥             any number less than the input
 I            assign it to I
  ṗ           must be prime
   -₆ṗ        minus 6 must also be prime
      ;I      append I again (so we have [I-6,I])

```
> 3 votes

# Answer
**Perl: 73 char**

```
sub p{(1x$_[0])!~/^(11+?)\1+$/}map{$x=$_+6;p($_)&&p($x)&&say"$_,$x"}2..<>

```

**usage:**

```
echo 30 | perl -E 'sub p{(1x$_[0])!~/^(11+?)\1+$/}map{$x=$_+6;p($_)&&p($x)&&say"$_,$x"}2..<>'

```

**output:**

```
5,11
7,13
11,17
13,19
17,23
23,29

```
> 2 votes

# Answer
# Octave 39

Modified my MATLAB answer to comply with the new (annoying) rules. `n` is your value.

```
p=@isprime;i=1:n;[j=i(p(i)&p(i+6));j+6]

```

Can be tested here
> 2 votes

# Answer
## R, 83 characters

```
f=function(n){library(gmp);p=isprime;for(i in 1:n)if(p(i)&p(i+6)){print(c(i,i+6))}}

```

Usage:

```
f(150)

```
> 2 votes

# Answer
# Ruby, 99 88 86 84 82 78

```
f=->x{(9..x).map{|n|[n-6,n]if[n,n-6].all?{|t|(2...t).all?{|m|t%m>0}}}.compact}

```

Sample output:

`[[5, 11], [7, 13], [11, 17], [13, 19], [17, 23], [23, 29], [31, 37], [37, 43], [41, 47], [47, 53], [53, 59], [61, 67], [67, 73], [73, 79], [83, 89]]`
> 2 votes

# Answer
## Ruby ~~75~~ 74

The new version uses Artem Ice's prime test method:

```
z=->x{(9..x).map{|i|[i-6,i]}.select{|a|a.all?{|r|(2...r).all?{|m|r%m>0}}}}

```

Online test: http://ideone.com/yaOdn
> 2 votes

# Answer
## JavaScript (~~140~~ 113 Characters)

`t=(i,n)=>{for(n=i;n%--i;);return 1==i};s=(n,p)=>{for(p=[],i=2;i<n-6;i++)if(t(i)&&t(i+6))p.push([i,i+6]);return p}`

Try `s(30)`.

Updated to use the shorter primality test from here, and to use the new arrow notation.

*Old version (140 characters):*

`function t(n,i){for(i=2;i<n;i++)if(!(n%i))return!1;return!0}function s(n,p){for(p=[],i=2;i<n-6;i++)if(t(i)&&t(i+6))p.push([i,i+6]);return p}`
> 2 votes

# Answer
# J, 25 chars

```
(#~*/"1@p:~&1)(,+&6)"0 i.

```

`i.n` creates a range of \[0,n)

`(,+&6)"0` takes each integer `n` in the list and makes a pair `n, n+6`

`(#~ condition)` is basically a `filter`, and the condition in this case, `*/"1@p:~&1`, just checks if a pair is composed solely of primes.
> 2 votes

# Answer
# C# (279 characters)

Basically, it's Saumil's solution with a couple of tweaks. I don't have ~~enough~~ any reputation for commenting though, so...

```
using System;namespace X{public class P{static int l=100;static void Main(){F(0);}static bool I(int n){bool b=1>0;if(n==1){b=1<0;}for(int i=2;i<n;++i){if(n%i==0){b=1<0;break;}}return b;}static void F(int p){if((p+6)<=l){if(I(p+6)&&I(p)){Console.WriteLine(p+6+","+p);}F(p+1);}}}}

```

**Output:**

```
11,5
13,7
17,11
19,13
23,17
29,23
37,31
43,37
47,41
53,47
59,53
67,61
73,67
79,73
89,83

```
> 2 votes

# Answer
# 05AB1E, 10 bytes

Outputs in reversed order, because the K3 answer also seems to do that.

```
LεD6-‚}ʒpP

```

Try it online!

# Explanation

```
L           Length range
 ε          Map:
  D             Duplicate
   6-           Minus 6
     ‚          Pair
      }         Reverse the pair
       ʒ    Filter:
        p       Is_prime
         P      in both items

```
> 2 votes

# Answer
# JavaScript (V8), ~~104~~ 75 bytes

*-29 bytes thanks to @emanresuA*

```
g=x=>--x>6&&g(x,(f=(n,t=2)=>t<n?n%t&&f(n,t+1):n>1)(x)*f(x-6)&&print(x-6,x))

```

Try it online!
> 2 votes

# Answer
# Jelly, 9 bytes

```
Rż+¥6ẒẠ$Ƈ

```

Try it online!

## How it works

```
Rż+¥6ẒẠ$Ƈ - Main link. Takes N on the left
R         - Range; R = [1, 2, ..., N]
   ¥6     - Previous 2 links as a dyad f(R, 6):
  +       -   Add 6 to each element in R
 ż        -   Zip together
       $Ƈ - Keep those pairs for which the following is true:
      Ạ   -   Are all elements...
     Ẓ    -   ...prime?

```
> 2 votes

# Answer
# Excel, 131 bytes

```
=LET(x,SEQUENCE(A1),y,TRANSPOSE(x),z,x*(MMULT((MOD(x,y)=0)*1,x^0)=2),a,IFERROR(INDEX(z,x+{0,6}),),FILTER(a,MMULT(SIGN(a),{1;1})=2))

```

Link to Spreadsheet

## Explanation

* `=LET(` allows defined names within formulas.
* `x,SEQUENCE(A1),` x = `1..A1` listed vertically.
* `y,TRANSPOSE(x),` y = `1..A1` listed horizontally.
* `(MOD(x,y)=0)*1` creates a matrix this is 1 if x mod y = 0 and 0 otherwise.
* `MMULT(~,x^0)` sums the elements of each row with matrix multiplication. `x^0` is a vertical matrix of 1s.
* `z,x*(~=2),` if the sum = 2 then `x` is prime and `z=x` else `z=0`.
* `,a,IFERROR(INDEX(z,x+{0,6}),),` creates an array `a` where the first column is `z` and the second is `z` offset by 6 rows.
* `FILTER(a,MMULT(SIGN(a),{1;1})=2)` returns the rows of `a` that have no zeros.
> 2 votes

# Answer
# Mathematica - 69 48 chars

Assuming m has been assigned a value

```
p=PrimeQ;Cases[Range@m,n_/;p@n&&p[n+6]:>{n,n+6}]

```
> 1 votes

# Answer
## C# 295

```
using System;using System.Linq;namespace K{class C{public static void Main(string[]a){Func<int,bool>p=i=>Enumerable.Range(2,i-3).All(x=>i%x>0);Console.WriteLine("["+String.Join(",",Enumerable.Range(0,int.Parse(a[0])).Where(i=>i>9&&p(i)&&p(i-6)).Select(i=>"["+(i-6)+","+i+"]").ToArray())+"]");}}}

```

Online test: http://ideone.com/4PwTW *(in this test I've replaced `int.Parse(a[0])` with the actual int value, as I cannot supply command line arguments to programs running on ideone.com)*
> 1 votes

# Answer
# Scala (82)

```
def p(n:Int)=9 to n map(x=>List(x-6,x))filter(_.forall(l=>2 to l-1 forall(l%_>0)))

```

Sample output: `Vector(List(5, 11), List(7, 13), List(11, 17), List(13, 19), List(17, 23), List(23, 29), List(31, 37), List(37, 43), List(41, 47), List(47, 53), List(53, 59), List(61, 67), List(67, 73), List(73, 79), List(83, 89))`
> 1 votes

# Answer
# Factor 140

This language is fun and interesting. My first script.

```
:: i ( n -- ? )
n 1 - 2 [a,b] [ n swap mod 0 > ] all? ;
:: s ( n -- r r )
11 n [a,b] [ i ] filter [ 6 - ] map [ i ] filter dup [ 6 + ] map ;

```

Usage:

```
( scratchpad ) 100 f

--- Data stack:
V{ 5 7 11 13 17 23 31 37 41 47 53 61 67 73 83 }
V{ 11 13 17 19 23 29 37 43 47 53 59 67 73 79 89 }

```
> 1 votes

# Answer
**PARI/GP (62 characters)**

```
f(a)=w=[];forprime(x=0,a,isprime(x+6)&w=concat(w,[[x,x+6]]));w

```

Example:

```
 (00:01) gp > f(a)=w=[];forprime(x=0,a,isprime(x+6)&w=concat(w,[[x,x+6]]));w
 (00:01) gp > f(30)
 %1 = [[5, 11], [7, 13], [11, 17], [13, 19], [17, 23], [23, 29]]

```
> 1 votes

# Answer
# Haskell (65 chars)

```
p n=[(x,x+6)|x<-[3..n-6],all(\k->all((>0).mod k)[2..k-1])[x,x+6]]

```

The output:

```
Prelude> p 100
[(5,11),(7,13),(11,17),(13,19),(17,23),(23,29),(31,37),(37,43),(41,47),(47,53),(
53,59),(61,67),(67,73),(73,79),(83,89)]

```

---

**About the MATLAB answer here:**

*(I spent all my rep on a bounty so can't comment just yet)*. Google says: " the Matlab's isprime function ... is based on the probabilistic Miller-Rabin". So it seems that the MATLAB entry should be disqualified.
> 1 votes

# Answer
## R ~~85~~ 81 characters

```
f=function(n){m=2:n;a=m[rowSums(!outer(m,m,`%%`))<2];cbind(b<-a[(a+6)%in%a],b+6)}

```

Example run:

```
f(50)
      [,1] [,2]
 [1,]    5   11
 [2,]    7   13
 [3,]   11   17
 [4,]   13   19
 [5,]   17   23
 [6,]   23   29
 [7,]   31   37
 [8,]   37   43
 [9,]   41   47

```
> 1 votes

# Answer
# PHP, 106 bytes

```
function p($n){for($i=$n;--$i&&$n%$i;);return$i-1;}for(;++$i<$argv[1]-5;)p($i)|p($k=$i+6)?:print"$i,$k\n";

```

program prints pairs as `n,n+6` delimited by linebreaks. Run with `-r`.

I modified my is\_prime function (& saved a byte) so that it returns `0` for primes to golf on the Elvis.
> 1 votes

# Answer
# CJam, 27 bytes

```
ri),{__6+_mp@mp&{pp}{;;}?}%

```

It prints pairs as two lines with one number each on then, largest to smallest. See the TIO for the example from the question.

Try it online

Explanation:

```
ri                              input an integer
  )                             increment
   ,{                    }%     iterate "m" from 0 to n-1
     __                         create two copies
       6+                       add 6
         _                      copy
          mp                    check if m+6 is prime
            @                   rotate so m is on top
             mp                 check if m is prime
               &                bitwise AND on two prime checks
                        ?       ternary if-else
                {pp}            if primes, print top two numbers
                    {;;}        otherwise, discard them

```
> 1 votes

# Answer
**C# ( 321 303 290 characters )**

`using System;namespace X{public class P{ static int l=100;static void Main(){F(0);}static bool I(int n){bool b=true;if(n==1){b=false;}for(int i=2;i<n;++i){if(n%i==0){b=false;break;}}return b;}static void F(int p){if((p+6)<=l){int m=p+6;if(I(m)&&I(p)){Console.WriteLine(m+","+p);}F(p+1);}}}}`

**Output:**
11,5
13,7
17,11
19,13
23,17
29,23
37,31
43,37
47,41
53,47
59,53
67,61
73,67
79,73
89,83
> 0 votes

# Answer
# Ruby, 61 bytes

```
->n{Prime.take_while{_1<=n}.map{[_1,_1+6]}.select{_2.prime?}}

```

Attempt This Online!
> 0 votes

# Answer
# POSIX Shell Command Language + Utilities + seq + 4.1BSD factor, 101 bytes

```
seq 2 $1|factor|sed '/: .* /d;s/:.*//'>q
while read a;do grep -x $((a+6)) q&&echo $a;done<q|paste - -

```

seq generates integers in \[2, specified\], factor turns them into this format we all know and love:

```
2: 2
3: 3
4: 2 2
5: 5
6: 2 3

```

sed deletes lines with a space after the first colon-space (i.e. non-primes), then trims off everything after the colon. For each prime a, we copy the prime equal to a+6 to the standard output stream, and if that succeeded, also write a, then we paste each pair of output lines together.

Any seq since its introduction in Version 8 AT&T UNIX works, and you can trivially replace it with a while at a cost of 42 bytes. Any factor since its introduction in Version 7 AT&T UNIX works (sans format quirks maybe, I'm not in the mood for reading PDP-11 assembly; if the format is space-less, then 4.1BSD probably has the right one).

Transcript of test cases:

```
$ cat d.sh; echo; wc -c d.sh
seq 2 $1|factor|sed '/: .* /d;s/:.*//'>q
while read a;do grep -x $((a+6)) q&&echo $a;done<q|paste - -
101 d.sh
$ ./d.sh 30
11      5
13      7
17      11
19      13
23      17
29      23

```

Herein an "array of arrays" is a set of lines containing tab-delimited fields.
> 0 votes

# Answer
# Japt, 11 bytes

```
õ í7ôU)fÈej

```

Try it
> 0 votes

---
Tags: code-golf, math, primes
---


title: Find the closest palindromic number

text:
# Question
Title: Find the closest palindromic number
Given a number *N*, output/return ***X* so that *N+X* is a palindrome, where *|X|* has to be as small as possible.**

**Palindrome:** A number is a palindrome, if its sequence of digits is the same when reading them from left to right as when reading from right to left.
`95359` and `6548456` are symmetric, `123` and `2424` are not. Numbers with leading zeros such as `020` are not a palindrome.

**Input** is a positive integer smaller than 1015. Read it from stdin, as a method-parameter, whatever.

**Output** has to be an integer (positive or negative) and ought to be 0 if the input is already a palindrom. You may write your output to stdout, return it from a function or whatever you like. If there are 2 numbers (e.g. `2` and `-2`) that satisfy the requirements, output only one of them.

**Examples:**

```
Input             Output
3                 0
234               -2
1299931           -10
126               5 or -5 (only one of them)

```

# Answer
# Pyth, 26 20

```
Lnb_bWP`+QZ=Z-g0ZZ)Z

```

Updated to meet the new rules.

The program runs in an infinite loop which tests every possible increment, in the order 0, -1, 1, -2, -2 ...

Explanation:

```
Q=eval(input())     implicit
Z=0                 implicit
Lnb_b               def P(b): return b != rev(b)
WP`+QZ              while P(repr(Q+Z)):
=Z-g0ZZ             Z=(0>=Z)-Z
)                   <end while>
Z                   print(Z)

```

Example run:

```
python3 pyth.py programs/palin.pyth <<< 965376457643450
-2969881

```

This took 23 seconds.

---

Bonus solution, same character count:

```
Wn`+QZ_`+QZ=Z-g0ZZ)Z

```
> 9 votes

# Answer
# Ruby, ~~111~~ 84 bytes

```
i=$*[j=-1].to_i
r=->j{s=(i+j).to_s
abort(j.to_s)if s==s.reverse}
loop{r[j+=1]
r[-j]}

```

Takes the number as its only command-line argument.
> 7 votes

# Answer
# CJam, ~~34~~ ~~29~~ 25 bytes

```
q~:I!{:R1<R-RI+`_W%=!}g;R

```

Try it online.

### Examples

```
$ cjam palfind.cjam <<< 120; echo
1
$ cjam palfind.cjam <<< 121; echo
0
$ cjam palfind.cjam <<< 122; echo
-1

```

### How it works

```
q~:I    " Read from STDIN, evaluate and save the result in “I”.                           ";
!       " Compute the logical NOT (0 since the integer is positive).                      ";
{       "                                                                                ";
  :R    " Save the topmost integer in “R”.                                                ";
  1<R-  " Compute (R < 1) - R. This produces the sequence 0 → 1 → -1 → 2 → -2 → … .       ";
  RI+   " Push I + R.                                                                     ";
  `_    " Cast to string and push a copy.                                                 ";
  W%=!  " Check if the reversed copy matches the original.                                ";
}g      " If it doesn't, repeat the loop.                                                 ";
;R      " Discard the integer on the stack and push “R”.                                  ";

```
> 6 votes

# Answer
# Python 2.7, ~~98~~, 81

Creates a palindrome from the input number, then subtracts that from the input to find the delta.

```
def f(n):
    m=map(int,str(n));l=len(m)/2;m[-l:]=m[l-1::-1];return int(`m`[1::3])-n

```

usage:

```
print f(3)          # 0
print f(234)        # -2
print f(2342)       # -10
print f(129931)     # -10
print f(100000)     # 1

```

ungolfed and annotated:

```
def f(n):                      # take a integer n
    m=map(int,str(n));         # convert n into array of ints
    l=len(m)/2;                # get half the length of the array of ints
    m[-l:]=m[l-1::-1];         # replace the last elements with the first elements reversed
    return int(`m`[1::3])-n    # convert array of ints backinto single int and subtract the original number to find the delta

```
> 5 votes

# Answer
# Haskell - 62

```
f n=[x-n|x<-[0..]>>= \v->[n+v,n-v],show x==(reverse.show)x]!!0

```

Save it to a file named `golf.hs` and then test it with ghci:

```
*Main> :l golf
[1 of 1] Compiling Main             ( golf.hs, interpreted )
Ok, modules loaded: Main.
*Main> map f [1000..1050]
[-1,0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10,-11,-12,-13,-14,-15,-16,-17,-18,-19,-20,-21,-22,-23,-24,-25,-26,-27,-28,-29,-30,-31,-32,-33,-34,-35,-36,-37,-38,-39,-40,-41,-42,-43,-44,-45,-46,-47,-48,-49]
*Main>

```
> 5 votes

# Answer
## Perl 5, 93 89 88 87 75 63 44

```
$/=($/<1)-$/while$_+$/-reverse$_+$/;$_=$/+0

```

Ungolfed:

```
while($input + $adjustment - reverse($input + $adjustment)) {
    $adjustment = ($adjustment < 1) - $adjustment;
}
$input = $adjustment + 0;  ## gives 0 if $adj is undefined (when $input is a palindrome)
print $input;  ## implicit

```

Thanks to Dennis's suggestions, got it down to 43 + `-p` = 44
> 4 votes

# Answer
# 05AB1E, ~~15~~ 14 bytes (-1 Thanks to Emigna)

```
2äнsgÈi∞ë.∞}s-

```

Try it online!

---

# Method:

* Take the first half of the number.
* Mirror it intersected if odd, non-intersected if even.
* Difference.
> 4 votes

# Answer
# Java : ~~127~~ 109

Basic iteration, checking both negative and positive before moving to the next candidate.

```
int p(long n){int i=0;for(;!(n+i+"").equals(new StringBuilder(n+i+"").reverse()+"");i=i<1?-i+1:-i);return i;}

```

For input `123456789012345`, it returns `-1358024`, to equal palindrome `123456787654321`.

Line breaks:

```
int p(long n){
    int i=0;
    for(;!(n+i+"").equals(new StringBuilder(n+i+"").reverse()+"");i=i<1?-i+1:-i);
    return i;
}

```
> 3 votes

# Answer
# Clojure, 92

Takes the first from a lazy for-sequence that works from 0 out and only includes values that make palindromes:

```
(defn p[x](first(for[i(range)j[1 -1]k[(* i j)]s[(str(+ x k))]:when(=(seq s)(reverse s))]k)))

```

REPL-LPER session:

```
golf-flog> (p 3)
0
golf-flog> (p 10)
1
golf-flog> (p 234)
-2
golf-flog> (p 1299931)
-10
golf-flog> (p (bigint 1e15))
1

```
> 3 votes

# Answer
# JavaScript (ES6), 84 bytes

```
n=>[...(''+n)].reduce((p,c,i,s,m=s.length-1)=>i<m/2?p+(c-s[m-i])*Math.pow(10,i):p,0)

```

My first golf challenge! I know the shorter and more elegant solution has already been posted by @Brian H., but this is another approach.

### Test Code

```
const t =
n=>[...(''+n)].reduce((p,c,i,s,m=s.length-1)=>i<m/2?p+(c-s[m-i])*Math.pow(10,i):p,0)
;

console.log('t(3) =', t(3)); // expected: 0
console.log('t(234) =', t(234)); // expected: -2
console.log('t(1299931) =', t(1299931)); // expected: -10
console.log('t(126) =', t(126)); // expected: -5
```
> 3 votes

# Answer
# Brachylog, 8 bytes

```
;.≜+A↔A∧

```

Try it online!

The label predicate  is vital here, because by using it on the output before anything else happens (although it's really being invoked on the list containing the input and the output), its absolute value is minimized, because instead of doing anything smarter based on the constraints the program guesses every integer starting from 0 until it can find one that works. If  is omitted, it dawns on the program that 0 is a very nice palindrome, and it will always output the negative of the input.

```
            The input
;  +        plus
 .          the output
  ≜         which is instantiated immediately
    A       is A
     ↔      which reversed
      A     is still A
       ∧    but isn't necessarily the output.

```
> 3 votes

# Answer
# JavaScript, 175 136 117

Straightforward. `p` returns true if a given number is palindrome, `f` searches the nearest.

**EDIT:** I also golfed it a little bit more thanks to the sweet "indecrement" trick by Geobits in the Java answer here.

```
p=function(n){return (s=''+n).split('').reverse().join('')==s}
f=function(n){for(i=0;!p(n+i);i=i<1?-i+1:-i);return i}

```

Usage:

```
f(3)
f(234)
f(1299931)

```
> 2 votes

# Answer
# J - 49 char

A function mapping integers to integers.

```
((0{g#f)>:@]^:(+:/@g=.(-:|.)@":@+f=._1 1*])^:_&0)

```

Here's how you might build to this result, in three parts. This is the display of the J REPL: indented lines are user input and outdented ones are REPL output. And yes, J spells the negative sign with an underscore `_`.

```
   236 (_1 1*]) 4                          NB. -ve and +ve of right arg
_4 4
   236 (f=._1 1*]) 4                       NB. name it f
_4 4
   236 (+f=._1 1*]) 4                      NB. add left to each
232 240
   236 (":@+f=._1 1*]) 4                   NB. conv each to string
232
240
   236 ((-:|.)@":@+f=._1 1*]) 4            NB. palindrome? on each
1 0
   236 (g=.(-:|.)@":@+f=._1 1*]) 4         NB. name it g
1 0
   236 (+:/@g=.(-:|.)@":@+f=._1 1*]) 4     NB. logical NOR (result 1 if both=0)
0
   palin =: (+:/@g=.(-:|.)@":@+f=._1 1*])

   236 (>:@]) 0                            NB. increment right
1
   236 (>:@]^:2) 0                         NB. functional power
2
   236 (>:@]^:(236 palin 3)) 3             NB. power 1 if no palindromes
4
   236 (>:@]^:(236 palin 4)) 4             NB. power 0 if has palindrome
4
   236 (>:@]^:palin) 4                     NB. syntactic sugar
4
   236 (>:@]^:palin^:_) 0                  NB. increment until palindrome, start with 0
4
   (>:@]^:(+:/@g=.(-:|.)@":@+f=._1 1*])^:_&0) 236    NB. bind 0
4
   delta =: >:@]^:(+:/@g=.(-:|.)@":@+f=._1 1*])^:_&0

   ((f) delta) 236       NB. f=: -ve and +ve
_4 4
   ((g) delta) 236       NB. g=: which are palindromes
1 0
   ((g#f) delta) 236     NB. select the palindromes
_4
   ((g#f) delta) 126     NB. what if both are equal?
_5 5
   ((0{g#f) delta) 126   NB. take the first element
_5
   ((0{g#f)>:@]^:(+:/@g=.(-:|.)@":@+f=._1 1*])^:_&0) 236   NB. it works!
_4

```

Examples:

```
   pal =: ((0{g#f)>:@]^:(+:/@g=.(-:|.)@":@+f=._1 1*])^:_&0)
   pal 3
0
   pal every 234 1299931 126
_2 _10 _5
   pal 2424
18
   2424 + pal 2424
2442

```

You can also make the golf prefer the positive solution over the negative when they're equal, by changing `_1 1` to `1 _1`.
> 2 votes

# Answer
# Javascript 86

```
n=>{s=(n+'').split('');for(i=0,j=s.length-1;i<j;i++,j--)s[j]=s[i];return s.join('')-n}

```

This is my first codegolf challenge. Hope this solution is acceptable.

ungolfed: `n => {
 s = (n + '').split('');
 for (i = 0, j = s.length - 1; i < j; i++,j--)
 s[j] = s[i];
 return s.join('') - n
}` Explanation:
Convert input n to String and split.
Iterate over both sides of the resulting array and copy digit on s\[i\] to s\[j\] until i \< j. This will result in our desired palindrome.
Join array back together and subtract n to get x
> 2 votes

# Answer
# C (clang), 85 bytes

```
f(n,x,y,z){for(x=0;z=n+x;x=(1>x)-x){for(y=0;z;z/=10)y=y*10+z%10;if(y==n+x)return x;}}

```

This turned out to be a port of isaacg's Pyth solution.

Try it online!
> 2 votes

# Answer
## Groovy - 131 111 107 chars

Golfed:

```
n=args[0] as long;a=n;b=n;f={if("$it"=="$it".reverse()){println it-n;System.exit 0}};while(1){f a++;f b--}

```

sample runs:

```
bash-2.02$ groovy P.groovy  0
0
bash-2.02$ groovy P.groovy  234
-2
bash-2.02$ groovy P.groovy  1299931
-10
bash-2.02$ groovy P.groovy  123456789012345
-1358024

```

Ungolfed:

```
n=args[0] as long
a=n
b=n
f={ if("$it"=="$it".reverse()) {
       println it-n
       System.exit 0
    }
}

while(1) {
    f a++
    f b--
}

```
> 1 votes

# Answer
# Python 2 - 76

```
i=input()
print sorted([r-i for r in range(2*i)if`r`==`r`[::-1]],key=abs)[0]

```

Gets the input number and generates a list of the differences between the input and every number between `0` and `2*i` only if the number is palindromic.

It then sorts the list by absolute value and prints the first element.
> 1 votes

# Answer
## C++ 289

Function P checks for palindromes using `<algorithm>` method.

Ungolfed:

```
bool P(int32_t i)
{
string a,b;
stringstream ss;
ss<<i;
ss>>a;
b=a;
reverse_copy(b.begin(),b.end(),b.begin());
int k=a.compare(b);
return (k==0);
}
int main()
{
int32_t n; cin>>n;
int32_t x=0,y=n,z=n,ans=x;
while(1)
{
if(P(y)){ans=x; break;}
if(P(z)){ans=-1*x; break;}
x++;
y+=x;
z-=x;
}
cout<<ans<<endl;
return 0;
}

```
> 1 votes

# Answer
## Mathematica 75

Probably can be golfed more..

```
p = (j=0; b=#; While[a=IntegerDigits[b]; b += ++j(-1)^j; a!=Reverse[a]]; #-b+(-1)^j) &

```

Spaces not counted and not needed.
> 1 votes

# Answer
# CoffeeScript: 73

```
(x)->(x+="")[0...(y=x.length/2)]+x[0...-y].split("").reverse().join("")-x

```

**Explanation:** This takes advantage of the fact that if we have a number of odd length (say 1234567), `x.slice(0, y)` won't include the middle digit but `x.slice(0, -y)` will. JavaScript's `slice` probably *shouldn't* work this way, but it does.

I was expecting CoffeeScript/JavaScript to have a better way to reverse a string, but the split/reverse/join method seems to be all there is.
> 1 votes

# Answer
# PHP, 56 bytes

```
for(;strrev($i+$n=$argv[1])-$n-$i;$i=($i<1)-$i);echo+$i;

```

takes input from command line argument; run with `-nr`.
> 1 votes

# Answer
# javascript 68 bytes

```
(n,s=[...(''+n)],j=s.length)=>s.map((v,i,)=>i>--j?s[j]:v).join('')-n

```

HUGE props to @Beldraith for the algorithm, i'm posting this as an answer though, because it took me quite the time to get it to work in a single statement.

Any tips are welcome ;)

### ungolfed

```
(
    n, // input
    s=[...(''+n)], // input split to array of chars
    j=s.length, // highest available index in s
)=>
s.map( // this will return a new array, without modifying s
    (
        v, // value of current iteration
        i, // index of current iteration
    )=> i > --j ? s[j] : v
).join('') - n

```
> 1 votes

# Answer
# Python 2, ~~55~~ 54 bytes

```
l=lambda n,d=0:`n+d`!=`n+d`[::-1]and l(n,~d+(d<0))or d

```

Try it online!
> 1 votes

# Answer
# Japt, 8 bytes

```
nÈ¥sw}cU

```

Try it

```
nÈ¥sw}cU     :Implicit input of integer U
      cU     :Get the first number in the sequence [U,U-1,U+1,U-2,U+2,...,U-n,U+n]
 È           :That returns true when passed the the following function
  ¥          :  Test for equality with
   s         :  Convert to string
    w        :  Reverse
     }       :End function
n            :Subtract U from the result

```
> 1 votes

# Answer
# Raku, 45 bytes

```
{($_,{++$*($*=-1)+$_}...{$_==.flip})[*-1]-$_}

```

Try it online!

* `$_, { ... } ... { ... }` defines a sequence that starts with the input argument `$_`.
* The first set of braces `{ ++$ * ($ *= -1) + $_ }` generates each term of the sequence from the previous one. It uses two anonymous state variables, both written as `$`. The first one increments on each call to the block, and the other alternates between -1 and +1. Multiplying them together and adding to the previous element gives the sequence `$_, $_ + 1, $_ - 1, $_ + 2, $_ - 2, ...`.
* The second set of braces `{ $_ == .flip }` is the terminating condition, met by the first number which is equal to itself with the digits flipped (reversed).
* `[* - 1]` picks the last element of the sequence (the palindromic one).
* `- $_` subtracts the input element to give the required difference.
> 1 votes

# Answer
Python, 109

```
def q(x,z):
 r=lambda s:int(str(s)[::-1])
 if x+z==r(x+z):return z
 if x-z==r(x-z):return -z
 return q(x,z+1)

```
> 0 votes

# Answer
## QBIC, 38 bytes, nc

```
:{[-1,1,2|A=!a+b*c$~A=_fA||_xb*c]c=c+1

```

Explanation:

The code reads an input, and then applies a modifier. It then tests to see if the number + modifier is a palindrome. Then, it flips the sigh on the modifier, re-applies that and tests again.

```
:{        Read the input value, start a DO-loop
[-1,1,2|  FOR (b = -1; b <= 1; b+=2 )
A=!a+b*c$ Get a string from the input number,
            plus modifier c (which is 0 at the start of QBIC)
            times -1 or 1, depending on b's iteration.
~A=_fA|   if that string is equal to it's own reversed version
|_xb*c]   then Quit, printing the modifier * sign
c=c+1     Increment the modifoer and DO-LOOP again.
          The DO-loop is implicitly closed by QBIC at EOF

```
> 0 votes

# Answer
# Axiom, ~~720~~ ~~594~~ 412 bytes

```
R(x)==>return x;p(r,a)==(n:=#(a::String);if r<0 then(a=0=>R a;n=1 or a=10^(n-1)=>R(a-1);a=10^(n-1)+1=>R(a-2));if r>0 then(n=1 and a<9=>R(a+1);a=10^n-1=>R(a+2));r=0 and n=1=>1;v:=a quo 10^(n quo 2);repeat(c:=v;w:=(n rem 2>0=>v quo 10;v);repeat(c:=10*c+w rem 10;w:=w quo 10;w=0=>break);r<0=>(c<a=>R c;v:=v-1);r>0=>(c>a=>R c;v:=v+1);R(c=a=>1;0));c)
D(a:NNI):INT==(p(0,a)=1=>0;w:=p(-1,a);s:=p(1,a);a-w<s-a=>w-a;s-a)

```

The byte count it is again this, but the algo it would be O(log(n)) because it would dipend only from the digit lenght of its input (and log10(n) would be near the lenght of the decimal digits of n). ungolfed and results

```
-- Ritorna il precedente numero palidrome rispetto ad 'a' NNI, se r<0
--                               ha la particolarita' palpn(-1,0) = 0
-- Ritorna il successivo numero palidrome rispetto ad 'a' NNI, se r>0
-- Se r=0 ritorna 1 se 'a' e' palindrome, 0 se 'a' non e' palindrome
R(x)==>return x
palpn(r,a)==
    n:=#(a::String) -- n la lunghezza in cifre di base 10 di a
    if r<0 then(a=0        =>R a;n=1 or a=10^(n-1)=>R(a-1);a=10^(n-1)+1=>R(a-2))
    if r>0 then(n=1 and a<9=>R(a+1);    a=10^n-1  =>R(a+2))
    r=0  and n=1=>1
    v:=a quo 10^(n quo 2)
    repeat -- because here not there is a goto instruction i have to use repeat
        c:=v;w:=(n rem 2>0=>v quo 10;v)
        repeat
          c:=10*c+w rem 10
          w:=w quo 10
          w=0=>break
        r<0=>(c<a=>R c;v:=v-1)
        r>0=>(c>a=>R c;v:=v+1)
        R(c=a=>1;0) -- for r==0
    c

-- Ritorna la distanza minima tra l'input 'a' e una palindrome:
--        0 se 'a' e' una palindrome
--        r numero con segno negativo se tale palindrome precede 'a'
--        r numero con segno positivo se tale palindrome e' successiva ad 'a'
palDistance(a:NNI):INT==
    palpn(0,a)=1=>0
    p:=palpn(-1,a);s:=palpn(1,a)
    a-p<s-a=>p-a
    s-a

--------------------------------------

(3) -> [[i,D(i)] for i in [3,10,234,1299931,126]]
   (3)  [[3,0],[10,1],[234,- 2],[1299931,- 10],[126,5]]
                                                  Type: List List Integer
(4) -> D 7978986575546463645758676970789089064235234524548028408198401348930489104890184018410
   (4)  - 199223418598327604580355025458434427119613
                                                            Type: Integer
(5) ->  p(0,7978986575546463645758676970789089064235234524548028408198401348930489104890184018410+%)
   (5)  1
                                                    Type: PositiveInteger
(6) -> 7978986575546463645758676970789089064235234524548028408198401348930489104890184018410+%%(-2)
   (6)
       7978986575546463645758676970789089064235234325324609809870796768575463646455756898797
                                                    Type: PositiveInteger

```
> 0 votes

# Answer
# Bash, 73 bytes

```
i=$1;x=$i;while((x-10#$(rev<<<$x)));do ((r=(1>r)-r,x=r+i));done;echo $x

```

Input goes to the 1st command line argument:

```
foo.sh 123456789

```
> 0 votes

# Answer
# Husk, ~~16 12~~ 9 bytes

```
ḟoS=↔+⁰İZ

```

Thanks @H.PWiz for -4 bytes!

Try it online!

### Explanation

```
ḟ(S=↔+⁰)İZ  -- input ⁰ a number, for example: 126
        İZ  -- built-in integers: [0,1,-1,2,-2...]
ḟ(     )    -- first element that satisfies the following (eg. 5):
     +⁰     --   add element to input: 131
  S=        --   is it equal to itself..
    ↔       --   ..reversed: 131 == 131

```
> 0 votes

# Answer
# APL NARS 47 chars

```
r←s a;b
r←0
A:b←⍕a+r⋄→0×⍳b≡⌽b⋄r←-r⋄→A×⍳r<0⋄r+←1⋄→A

```

this above search but algo can not be fast and right as the g below...

This

```
A:b←⍕a+r⋄→0×⍳b≡⌽b⋄r←-r⋄→A×⍳r<0⋄r+←1⋄→A

```

is a simple loop exit only when it find b≡⌽b so b is a string palindrome

```
  s¨3,10,234,1299931,126
0 1 ¯2 ¯10 5

∇r←g w;n;a;y;t;o;h;v
         r←0J1
   →0×⍳0≠⍴⍴w⋄→0×⍳''≡0↑w ⍝ if arg is not scalar int>=0→0J1
   →0×⍳(w<0)∨w≠⌊w
   h←{z←⍕⍺⋄q←⍕⍵⋄⍎(z,⌽q)}⍝ h return as digit ⍺⌽⍵
   n←⍴⍕w⋄r← 0
   →0×⍳n≤1              ⍝ arg one digit return r←0
   a←10*⌊n÷2
B: v←a⋄→C×⍳∼2∣n⋄v←a×10
C: t←⌊w÷v ⋄y←⌊w÷a
   o←y h t⋄r←(y+1)h t+1
   →D×⍳∼(∣r-w)<∣o-w⋄r←r-w⋄→0
D: r←o-w
∇

  g¨3,10,234,1299931,126
0 1 ¯2 ¯10 ¯5

```
> 0 votes

# Answer
# Ruby, 61 bytes

Port of ArBo's Python 2 answer.

```
->n,d=0{(n+d).to_s!=(n+d).to_s.reverse ? F[n,~d+(d<0?1:0)]:d}

```

Attempt This Online!
> 0 votes

# Answer
# Ly, 23 bytes

```
n:[s>lSrJl=[<f-u;]pp<`]

```

Try it online!

At a high level, this one keeps the original number on the stack, then increments a value on the backup cell for the "is this a palindrome?" test. That test is done one a separate stack using a simple "convert number to digits", reverse the stack, "convert digits to number" check.

```
n:                      - get the input number, make a copy we can increment
  [                   ] - infinite loop, the code exit once it finds the answer
   s>l                  - save the current candidate, switch stacks and load it
      SrJ               - convert to digits, reverse, convert back to a number
         l=             - re-load the candidate and compare
           [     ]      - codeblock used if they match (is palindrome)
            <           - switch back to the main stack
             f-         - flip the top two and subtract to get the offset
               u;       - print as a number and exit
                  pp    - delete stack
                    <`  - switch back to main stack and increment candidate

```
> 0 votes

---
Tags: code-golf, integer, palindrome
---


title: Prime Up your code

text:
# Question
Title: Prime Up your code
# Input

no input for this challenge

# The Challenge

Write a code that outputs:
**The first 10 prime numbers whose sum of their digits equal the number of bytes of your code**

# Examples

Let's say your code is `Co&%423@k"oo"` which is `13 bytes`
your code must output `[67, 139, 157, 193, 229, 283, 337, 373, 409, 463]`
those are the first 10 prime numbers whose sum.... ok you got it!

If your code is `8 bytes`, you must output `[17, 53, 71, 107, 233, 251, 431, 503, 521, 701]`

# Rules

You must **only use the first 10^8 prime numbers**
***which means all your numbers must be \<2038074743=10^8th prime***

If you **can't find 10 prime numbers in this range** that fit your bytes, then you will have to adjust your code (you may even have to add some bytes!) in order to find a "***working number of bytes***"

Just **output the 10 primes** in any way you like

This is , so the shortest code in bytes win!

# Answer
# Neim, ~~10~~ ~~8~~ 7 bytes

*-1 byte thanks to ASCII-only.*

```
πᛦΛ7

```

Try it online!

Outputs:

```
[7 43 61 151 223 241 313 331 421 601]

```

This (well, at least the approach) is ungolfable.

## Explanation

```
πᛦΛ7

π        push 13 (yes, very unintuitive :P)
 ᛦ       square (13² = 169)
        push the first 169 primes
   Λ     filter those that when the following are executed, evaluate to 1
        sum its digits and...
     7  check for equality against 7

```
> 15 votes

# Answer
# Jelly, 14 bytes

```
‘ÆNDS=14ø⁵#‘ÆN

```

Try it online!

This prints:

```
[59, 149, 167, 239, 257, 293, 347, 383, 419, 491]

```

**How it works**

```
‘ÆNDS=14ø⁵#‘ÆN
          #     Count the first
         ⁵        10
                Non-negative integers which meet:
‘ÆN               the (z+1)-th prime  (1-indexed :*()
   D              digits
    S             sum
     =            equals
      14          14
           ‘ÆN  Get those primes

```
> 9 votes

# Answer
# Pyth, 14 bytes

```
.f&qsjZT14P_ZT

```

**Try it here.**

This is 14 bytes and prints:

```
[59, 149, 167, 239, 257, 293, 347, 383, 419, 491]

```

# Pyth, 16 bytes

```
.f&qssM`Z16P_ZTZ

```

**Try it here!**

Note that this could be 15 bytes: `.f&qssM`Z16P_ZTZ`, but there are no primes that have 15 as the sum of their digits, since `15` is divisible by `3`, which would imply the number would also be divisible by `3`, hence not being prime.

This is 16 bytes long and prints:

```
[79, 97, 277, 349, 367, 439, 457, 547, 619, 673]

```

---

# How?

### Explanation 1

```
.f&qsjZT16P_ZT - Full program.

.f&           T  - First 10 numbers that satisfy the following:

           P_Z     - Are prime and
    sjZT           - And their sum of digits
   q     14        - Equals 14.

```

### Explanation 2

```
.f&qssM`Z16P_ZTZ - Full program.

.f&           T  - First 10 numbers that satisfy the following:

           P_Z     - Are prime and
    ssM`Z          - And their sum of digits
   q     16        - Equals 16.

```
> 6 votes

# Answer
# Jelly,  ~~14~~  13 bytes

```
DS⁼13
.ȷÆRÇÐf

```

**Try it online!**

### How?

```
DS⁼13 - Link 1, test digit sum equals thirteen: number, n
D     - get a list of the decimal digits of n
 S    - sum them
  ⁼13 - equals thirteen?

.ȷÆRÇÐf - Main link: no arguments
.ȷ      - literal 500
  ÆR    - prime range (all primes less than or equal to 500)
     Ðf - filter keep if:
    Ç   -   call last link (1) as a monad

```
> 6 votes

# Answer
## Husk, 13 bytes

```
↑10fȯ=13ΣdfṗN

```

Try it online!

### Explanation

```
            N    Take the (infinite) list of all natural numbers.
          fṗ     Select only the primes.
   fȯ            Filter again by the result of composing the following three functions:
         d         Get the decimal digits.
        Σ          Sum them.
     =13           Check whether the sum equals 13.
↑10              Take the first 10 primes in the result.

```
> 6 votes

# Answer
# Haskell, ~~77~~ 71 bytes

```
x=take 10[i|i<-[1..],sum(read.pure<$>show i)==71,all((>0).rem i)[2..i-1]]

```

Try it online!

*Saved 6 bytes thanks to Laikoni*

*For 71 bytes:*

```
[89999999,99899999,99998999,99999989,189989999,189998999,189999989,197999999,199898999,199979999]

```

> all your numbers must be \<2038074743

1999999999 is the number with the maximum sum of digits in the allowed range, and that sum is 82. Any program that is beyond 82 bytes will not satisfy the condition. I hope that 77 bytes is ok, but I don't know (it's still running on my computer).

**EDIT:** a slightly optimized version gave for 77 bytes:

```
[699899999,779999999,788999999,789999989,797999999,798899999,799898999,799899899,799999799,879999899]

```
> 6 votes

# Answer
# Brachylog, 13 bytes

```
{.≜ṗẹ+13∧}ᶠ¹⁰

```

Try it online!
> 5 votes

# Answer
# 05AB1E, 10 bytes

```
83LØʒSOTQ}

```

Try it online!

The `}` is used as a filler, since 9 is an invalid byte count.

Output: `[19, 37, 73, 109, 127, 163, 181, 271, 307, 433]`

## Explanation

```
83L        Push array [1, ..., 83], since 433 is the 83rd prime
   Ø       Map each to the nth prime
    ʒ      Get elements that return 1
     SO     When the sum of the digits
        Q   Equals
       T    10

```

---

# Almost 8 bytes

This would be valid if one more byte could be golfed off.

```
žyLØʒSO8Q

```

Try it online!

Output: `[17, 53, 71, 107, 233, 251, 431, 503, 521, 701]`

## Explanation

```
žy          Push number 128, since 701 is the 125th prime
  L         Push array [1, ..., 128]
   ØʒSO8Q   Map to nth primes and filter to those with a digit sum of 8 (see above)

```
> 5 votes

# Answer
# Mathematica, 52 bytes

```
Select[Prime@Range[10^6],Tr@IntegerDigits@#==52&,10]

```

> {799999,998989,999979,1789999,1798999,1979899,1989979,1997899,1999969,2599999}

thanx to @Not a tree for -6 bytes
> 3 votes

# Answer
# J, 29 bytes

```
(#~(29=[:+/"."0@":)"0)p:i.872

```

Try it online!

Definitely works on the REPL, probably works a regular program too (not sure how J does output for programs to be honest).

First pass, not particularly ideal but I can't think of any more clever approaches. Going to investigate hardcoding a smaller sequence.

# Explanation

```
(#~(29=[:+/"."0@":)"0)p:i.872
                      p:i.872  First 872 primes
 #~                            Filter by
   (29=[:+/"."0@":)"0            Digital sum = 29
                   "0              For each
                ":                 Convert to string
           "."0                    Convert each character to a number
         +/                        Sum results
    29=                            Equate to 29

```

872 guarantees that only the first 10 primes whose digital sum is 29 will be used.
> 2 votes

# Answer
# , 73 71 bytes

```
i8aa9
998a99
a98a
aa89
18998a9
18a8a
18a9989
197aa
199898a
1a7a9Ía/999

```

Try it online!

Simple substring replacement compression - I checked all the possible answer outputs, and then did some "which one has a simple string replacement that saves most characters" testing. e.g. generating this table. \[edit: I looked again at the table and saw I could do the 71 byte version instead\].

The higher primes have more long runs of 9 in them, and the best I found was where the digits add up to 73, the pattern 89999 -\> 1 char brings the text down from 99 bytes to 63 bytes. Finding a way to undo 'a' -\> '89999' in the remaining 10 bytes led me to V.
> 2 votes

# Answer
# Japt, 19 bytes

```
AÆ_j ©19¥Zì x «X´}a

```

Try it online! with the `-Q` flag to format the array.

Outputs the first 10 primes whose digits add to `19`:

```
[199, 379, 397, 487, 577, 739, 757, 829, 883, 919]

```

Note that this could be golfed to 18 bytes (`ì x``ìx`), but no primes with a digit sum of 18 exist.

## Explanation

Map the array `[0, ..., 9]` by the following function, where `X` is the current value.

```
  _              }a

```

Return the first integer that returns true from the following function, where `Z` is the current value

```
   j ©

```

Check if this number is prime, and...

```
      19¥Zì x

```

The sum (`x`) of the digits (`ì`) in `Z` equals (`¥`) 19,

```
              «X´

```

And `X` is falsy (`«` is "and not", or `&&!`). This also decrements `X` (`´`).

Resulting array is implicitly outputted.
> 1 votes

# Answer
# Japt, ~~19~~ 11 bytes

Would be 12 if not for a bug in Japt's `j` function method, which would have necessitated padding it out to 13 as there are no primes with a digit sum of 12.

```
Èj «BaXìx}j

```

Test it

```
Èj «BaXìx}j
È               :Function taking an integer X as argument
 j              :  Is prime?
   «            :  Logical AND with logical NOT of
    B           :    11
     a          :    Absolute difference with
      Xì        :      Digit array of X
        x       :      Reduced by addition
         }      :End function
          j     :Get the first 10 integers >=0 that return true

```
> 1 votes

# Answer
# PARI/GP, 40 bytes

```
select(x->sumdigits(x)==40,primes(8600))

```

Not much golf about it (select those `x` with sum of digits 40 among first 8600 primes). Output is:

```
[49999, 68899, 69997, 77899, 78889, 78979, 79699, 79987, 85999, 88789]

```
> 1 votes

# Answer
# Pyke, 10 bytes

```
~p#.cTq)T>

```

Try it here!

```
~p         -   primes
  #.cTq)   -  filter(^)
   .c      -    digit_sum
     Tq    -   ^ == 10
        T> - [:10]

```
> 1 votes

# Answer
# Ruby 2.4.1, 74 Bytes

I was never going to beat one of the Codegolf optimised languages, but it was still fun to do it in Ruby. Frustrating that Prime is not in Core but in instead in the standard library. I am also frustrated that I can't beat Haskell.

```
2.4.1 :014 > require'prime';2.step.lazy.select{|n|n.digits.sum==74&&n.prime?}.first(10)
=> [389999999, 398999999, 498989999, 498998999, 499898999, 499899989, 499979999, 499989989, 579989999, 588999899]

```
> 1 votes

# Answer
# Ruby `-rprime`, 49 bytes

```
p  *Prime.lazy.select{_1.digits.sum==49}.take(10)

```

Attempt This Online!
> 1 votes

# Answer
# Vyxal, 8 bytes

```
æ*∑8=)₀ȯ

```

Try it online!
> 1 votes

# Answer
# Paradoc (v0.2.7+), 10 bytes (CP-1252)

```
5h¶fφTBŠT=

```

Try it online!

```
5h         .. 5 hundred
  ¶        .. Check if a number is prime...
   f       .. ...filter by the preceding block; converts 500
           .. to the range [0, 1, ..., 499]
    φ      .. Filter by the following block:
     T     .. Ten
      B    .. Base; convert to base-10 digits
       Š   .. Sum, resulting in the digit sum
        T  .. Ten
         = .. Check if (the digit sum and ten are) equal

```

Somewhat questionable since it prints all the numbers with no separator between them. An 11-byte program that prints each number on a separate line:

```
nIè¶fφTBŠE=

```

The only thing worth mentioning about it is the upper bound that's slightly more difficult to construct:  is 18² = 324.
> 0 votes

# Answer
# Bubblegum, 37 bytes

```
00000000: 0dc6 3901 4031 0c80 5043 9dfe 9180 7f63  ..9.@1..PC.....c
00000010: 6579 f028 9ed7 352d e7a3 4f48 37ff 9164  ey.(..5-..OH7..d
00000020: 4c96 04f7 02                             L....

```

Try it online!

Output is `29989,39799,39979,48799,48889,49789,56989,58699,58789,58897`
> 0 votes

---
Tags: code-golf, primes, source-layout
---


title: 1 to N column and row sums

text:
# Question
Title: 1 to N column and row sums
# Inspiration

There is a problem on the most recent AMC 12B test, the one held on November 16, 2022, which goes like this:

> (AMC 12B 2022, Question 17)
> How many \\$4\times4\\$ arrays whose entries are \\$0\\$s and \\$1\\$s are there such that the row sums (the sum of the entries in each row) are \\$1\\$, \\$2\\$, \\$3\\$, and \\$4\\$, in some order, and the column sums (the sum of the entries in each column) are also \\$1\\$, \\$2\\$, \\$3\\$, and \\$4\\$, in some order? For example, the array $$\begin{bmatrix}1&1&1&0\\0&1&1&0\\1&1&1&1\\0&1&0&0\end{bmatrix}$$satisfies the condition.

(If any of you are curious the answer is \\$576\\$.)

# Task

Your task is, given some positive integer \\$N\\$, output all \\$N\times N\\$ binary matrices such that the row sums are \\$1,2,\ldots,N\\$ in some order, as well as the column sums.

# Test Cases

```
N ->
Output
-------
1 ->
1

2 ->
1 1
1 0

1 1
0 1

1 0
1 1

0 1
1 1

3 ->
1 0 0
1 1 0
1 1 1

1 0 0
1 0 1
1 1 1

0 1 0
1 1 0
1 1 1

0 1 0
0 1 1
1 1 1

0 0 1
1 0 1
1 1 1

0 0 1
0 1 1
1 1 1

1 0 0
1 1 1
1 1 0

1 0 0
1 1 1
1 0 1

0 1 0
1 1 1
1 1 0

0 1 0
1 1 1
0 1 1

0 0 1
1 1 1
1 0 1

0 0 1
1 1 1
0 1 1

1 1 0
1 0 0
1 1 1

1 1 0
0 1 0
1 1 1

1 0 1
1 0 0
1 1 1

1 0 1
0 0 1
1 1 1

0 1 1
0 1 0
1 1 1

0 1 1
0 0 1
1 1 1

1 1 0
1 1 1
1 0 0

1 1 0
1 1 1
0 1 0

1 0 1
1 1 1
1 0 0

1 0 1
1 1 1
0 0 1

0 1 1
1 1 1
0 1 0

0 1 1
1 1 1
0 0 1

1 1 1
1 0 0
1 1 0

1 1 1
1 0 0
1 0 1

1 1 1
0 1 0
1 1 0

1 1 1
0 1 0
0 1 1

1 1 1
0 0 1
1 0 1

1 1 1
0 0 1
0 1 1

1 1 1
1 1 0
1 0 0

1 1 1
1 1 0
0 1 0

1 1 1
1 0 1
1 0 0

1 1 1
1 0 1
0 0 1

1 1 1
0 1 1
0 1 0

1 1 1
0 1 1
0 0 1

```

# Note

The reason why I'm not doing a challenge on simply outputting the number of matrices that satisfy the condition is because there is a pretty simple formula to calculate that number. Brownie points if you can figure out that formula, and why it works!

---

This is , so shortest code in bytes wins!

# Answer
# Jelly, 8 bytes

```
Œ!cþþ`ẎṠ

```

A monadic Link that accepts a positive integer and yields a list of the binary matrices.

**Try it online!**

### How?

We can first arrange the set of \\$N\\$ *sorted* rows any way we like leading to \\$N!\\$ matrices with sorted rows. Each of these matrices will have column sums from \\$1\\$ through to \\$N\\$ *in order*, so all column-wise permutations will be distinct, so there are \\$N!^2\\$ such matrices.

We can create these matrices by noting that each number in the set \\$\[1,N\]\\$ is greater than or equal to exactly \\$N\\$ of the elements in the set (including itself).

Thus a table of \\$\geq\\$ between two permutations of the first \\$N\\$ natural numbers is such a table, e.g.:

| \\$\geq\\$ | 1 | 3 | 2 |
| --- | --- | --- | --- |
| 3 | 0 | 1 | 0 |
| 2 | 0 | 1 | 1 |
| 1 | 1 | 1 | 1 |

Where one permutation defines the column sums (directly - i.e. \\$\\{1,3,2\\}\\$, above) and the other defines the row sums (in reverse order - i.e. \\$\\{3,2,1\\}\\$, above, defines the sums \\$\\{1,2,3\\}\\$)

```
Œ!cþþ`ẎṠ - Link: integer, N
Œ!       - all permutations (of [1..N])
     `   - use as both arguments of:
    þ    -   table of:
   þ     -     table of:
  c      -       n-choose-k (a golf to get a positive integer when n>=k else 0)
      Ẏ  - tighten to a list of the sub-tables
       Ṡ - sign (convert the positives to ones)

```
> 7 votes

# Answer
# APL (Dyalog Classic), ~~34~~ 33 bytes

```
{{~⍉¨⍵∘.⍀⍨↓∘.≠⍨⍳1+≢⊃⍵}⍣2⍣⍵⊂0 0⍴⍬}

```

Try it online!

Returns an array of boxed matrices. +1 for a flat structure by putting `,` somewhere in the first few characters.

Illustrates another way to get \\$f(N)=N!^2\\$:
For each \\$N\times N\\$ matrix that satisfies this property, we can invert 0s and 1s, then insert a row and column of 1s to get a \\$(N+1)\times(N+1)\\$ matrix that also has this property. Furthermore, each such resulting matrix is uniquely determined by predecessor, row, and column. Since there are \\$N+1\\$ positions in which a row or column can be inserted, \\$f(N+1)=(N+1)^2f(N)\\$, and \\$f(0)=1\\$ (one empty matrix) completes the induction.

```
base 0x0 matrix                                  ⊂0 0⍴⍬
⍵ times:                {                   }  ⍣⍵
  1...N+1                             ⍳1+≢⊃⍵
  N+1 row inserts           ⍵∘.⍀⍨↓∘.≠⍨
  N+1 column inserts      ⍉¨                 ⍣2
  invert                 ~

```
> 7 votes

# Answer
# , 27 22 bytes

```
i.@!([A."1"{A.)>:/~@i.

```

Try it online!

*-5 thanks to ovs!*

Create the "step" matrix, get all row permutations, then to each of those apply all permutations again, but to each row at the same time -- this is equivalent to applying it to the columns.
> 4 votes

# Answer
# Vyxal, 11 bytes

```
ɾ:v≤Ṗv∩vṖÞf

```

Try it Online!

```
ɾ           # Push range(1, n+1)
  v         # Over each...
ɾ: ≤        # Check if it's less than each of range(1, n+1)
    Ṗ       # Get all permutations
     v∩     # Transpose each
       vṖ   # Get permutations of each
         Þf # Flatten by one layer

```
> 3 votes

# Answer
# Python \+ NumPy, 94 bytes

```
from numpy import*
f=lambda n,p=0:1//n*[e:=eye(n)]or[1-w.T@e[j]for j in e<1for w in f(n+p,~p)]

```

Attempt This Online!

Same logic as before but implemented in matrix algebra avoiding he expensive `insert`.

### Python 3 \+ NumPy, 96 bytes (@att)

```
from numpy import*
f=lambda n,p=0:[insert(w,i,1+p,p)for i in r_[:n]for w in f(n+p,~p)]or[eye(0)]

```

Try it online!

### Python 3 \+ NumPy, 99 bytes

```
from numpy import*
f=lambda n,p=1:[insert(w,i,p,p)for i in r_[:n+1-p]for w in f(n-p,1-p)]or[eye(0)]

```

Try it online!

This works by alternating between inserting rows of zeros and columns of ones at every possible position.
> 3 votes

# Answer
# PARI/GP, 62 bytes

```
n->forperm(n,p,forperm(n,q,print(matrix(n,n,x,y,p[x]>=q[y]))))

```

Attempt This Online!

Let \\$p\\$ and \\$q\\$ runs over all permutations of \\$1,\dots,n\\$. For each \\$p\\$ and \\$q\\$, construct an \\$n\times n\\$ binary matrix where the element at position \\$(x,y)\\$ (\\$1\\$-indexed) is \\$1\\$ if and only if \\$p\[x\]\ge q\[y\]\\$.
> 2 votes

# Answer
# Nibbles, 8.5 bytes (17 nibbles)

```
+.;``p,$.@.$._`$/

```

Port of Jonathan Allan's Jelly answer: upvote that.
Sadly, Nibbles comes-out half-a-byte longer.

```
      ,$            # 1..input
   ``p              # get all permutations of that
  ;                 # and save this list of lists
 .                  # now map over each list
        .@          #   mapping over each saved list
          .$._      #     element-wise mapping over each x,y
              `$    #       sign of
                /   #       x integer-divided by y
+                   # finally, flatten by one level

```
> 2 votes

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

```
n=>P(n).flatMap(x=>P(n).map(y=>x.map(u=>y.map(v=>u+v<n))))
P=(n,i=n)=>n?i--?[...P(n,i),...P(--n).map(r=>r.splice(i,0,n)&&r)]:[]:[[]]

```

Try it online!
> 2 votes

# Answer
# Python 3, ~~147~~ 145 bytes

```
lambda n:[[[k[l]for l in j]for k in i]for j in p(range(n))for i in p([1]*i+[0]*(n-i)for i in range(1,n+1))]
from itertools import*;p=permutations

```

Try it online!

Based on my comment to this challenge. First generates a right triangular shaped matrix of 1s, then makes all possible different permutations of rows and columns. Outputs a list of 2D lists. -2 bytes thanks to Mukundan314.

---

# Python 3, ~~132~~ ~~121~~ ~~116~~ 115 bytes

```
lambda n:[[[1-(l>k)for l in j]for k in i]for i,j in product(*[[*permutations(range(n))]]*2)]
from itertools import*

```

Try it online!

Uses the method entailed in Jonathan Allan's answer. -12 bytes thanks to Mukundan314, -5 bytes thanks to att.
> 1 votes

# Answer
# Ruby, ~~125 ...~~ 79 bytes

```
->n{a=*[*1..n].permutation;a.product(a).map{|r,c|r.map{|x|c.map{|y|x>y ?0:1}}}}

```

Try it online!

Switched to Jonathan Allan's approach.
> 1 votes

# Answer
# Jelly, 11 bytes

```
>€ḶŒ!Z€Œ!€Ẏ

```

Try it online!

Port of my Vyxal.

```
 €          # Over each of...
            # implicit range(1, n+1)
>           # Are they greater than...
  Ḷ         # range(0, n)
   Œ!       # Permutations
     Z€     # Transpose each
       Œ!€  # Permutations of each
          Ẏ # Flatten by one level

```
> 0 votes

# Answer
# 05AB1E, 8 bytes

```
LœDδδ@€`

```

Port of *@JonathanAllan*'s Jelly answer, so make sure to upvote him as well!

Try it online or verify all test cases.

**Explanation:**

```
L         # Push a list in the range [1, (implicit) input]
 œ        # Get all permutations of this list
  D       # Duplicate it
   δ      # Apply double-vectorized:
    δ     #  Apply double-vectorized:
     @    #   a >= b check
      €`  # Then flatten the list of lists of matrices one level down
          # (after which the result is output implicitly)

```
> 0 votes

# Answer
# JavaScript (ES6), 146 bytes

This is a naive solution based on bit masks and brute force.

Prints all valid matrices.

```
n=>{for(k=1<<n*n;k--;M+2>>n-~n&&console.log(m))for(M=m=[],y=n;y--;M|=1<<r|1<<c+n)for(m[y]=[c=r=0],x=n;x--;r+=q,c+=k>>x*n+y&1)m[y][x]=q=k>>y*n+x&1}

```

Try it online!

### Commented

```
n => {                      // n = input
  for(                      // first loop:
    k = 1 << n * n;         //   start with k = 2 ** (n * n)
    k--;                    //   decrement until k = 0
    M + 2 >> n - ~n         //   if bits 1 to n * 2 (0-indexed)
    &&                      //   are all set in M:
      console.log(m)        //     print the matrix
  )                         //
    for(                    //   second loop:
      M =                   //     M = bit mask
      m = [],               //     m[] = matrix
      y = n;                //     start with y = n
      y--;                  //     decrement until y = 0
      M |= 1 << r |         //     update the bit mask
           1 << c + n       //     with row and column bits
    )                       //
      for(                  //     third loop:
        m[y] = [c = r = 0], //       initialize m[y], c and r
        x = n;              //       start with x = n
        x--;                //       decrement until x = 0
        r += q,             //       increment r if q is set
        c += k >> x * n + y //       increment c if the cell at
             & 1            //       (y, x) is set
      )                     //
        m[y][x] =           //       set m[y][x] to
        q =                 //       q, defined as
          k >> y * n + x    //       the cell at (x, y)
          & 1               //
}                           //

```
> 0 votes

# Answer
# Charcoal, 37 bytes

```
≔…⁰Ｎθ⊞υ⟦⟧Ｆθ≔ΣＥυＥ⁻θκ⁺κ⟦μ⟧υＦ⊕υＥυＥι⭆κ›μξ

```

Attempt This Online! Link is to verbose version of code. Explanation: Based on @Ausername's Vyxal answer.

```
≔…⁰Ｎθ

```

Start with a range from `0` to `N`.

```
⊞υ⟦⟧Ｆθ≔ΣＥυＥ⁻θκ⁺κ⟦μ⟧υ

```

Generate all of the permutations of that range.

```
Ｆ⊕υＥυＥι⭆κ›μξ

```

Generate the comparison matrices between each pair of incremented permutation and permutation.
> 0 votes

---
Tags: code-golf, number, binary-matrix
---


# Question
Title: Convert n strings of m length to m strings of n length
Write a program that, given any 'n' number of strings of 'm' length, returns 'm' number of 'n'-length strings, with this condition:

**Every new string should contains the letters at the same index of the others strings**

For example, the first output string must contain the first letter of all the input strings, the second output string must contain the second letter of all the input strings, and so on.

Examples (the numbers under the letters are the indexes of the strings):

```
input: "car", "dog", "man", "yay"
        012    012    012    012
output: "cdmy", "aoaa", "rgny"
         0000    1111    2222

input: "money", "taken", "trust"
        01234    01234    01234
output: "mtt", "oar", "nku", "ees", "ynt"
         000    111    222    333    444

```

Assume that the input is correct everytime

Shortest bytes' code wins!

**Edit:**

Since there are many programming languages, and there could be many possible solutions for each of them, I will post the shortest solution for each programming language and the user who provided it. Keep coding!

**Re-Edit:**

Thanks to user Dennis I inserted a snippet for the leaderboards.

```
var QUESTION_ID=85255,OVERRIDE_USER=56179;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
## Pyth, 1 byte

```
C

```

Try it here

Another transpose builtin
> 21 votes

# Answer
# Python, ~~36~~ 29 bytes

`zip(*s)` returns a list of tuples of each character, transposed.

```
lambda s:map(''.join,zip(*s))

```

**Try it online**
> 9 votes

# Answer
# Jelly, 1 byte

```
Z

```

Try it online!
> 8 votes

# Answer
# Vim, ~~37~~ 36 keystrokes

All the other answers are boring, and using boring single-byte builtins. Here's a hacky answer that does the entire thing manually, in something that isn't even a programming language:

```
Gmaqqgg:s/./&<cr>d<C-v>`aGo<esc>pvGgJ@qq@q`adgg

```

Explanation:

```
G                                   "move to the end of this line
     ma                             "And leave mark 'a' here
       qq                           "Start recording in register 'q'
         gg                         "Move to the beginning
           :s/./&<cr>               "Assert that there is atleast one character on this line
                      d             "Delete
                       <C-v>        "Blockwise
                            `a      "Until mark 'a'

    G                               "Move to the end of the buffer
     o<esc>                         "Open a newline below us
           p                        "And paste what we deleted
            vG                      "Visually select everything until the end
              gJ                    "And join these without spaces
                @q                  "Call macro 'q'. The first time, this will do nothing,
                                    "The second time, it will cause recursion.
                  q                 "Stop recording
                   @q               "Call macro 'q' to start it all

```

Now, everything is good, but the buffer has some extra text left over. So we must:

```
`a                              "Move to mark 'a'
  dgg                           "And delete everything until the first line

```
> 8 votes

# Answer
# MATL, 1 byte

```
!

```

**Try it online!**

Takes input implicitly, transposes, displays output implicitly.
> 7 votes

# Answer
## PowerShell v2+, ~~66~~ 54 bytes

```
param($n)for($x=0;$n[0][$x];$x++){-join($n|%{$_[$x]})}

```

Yo ... no `map`, no `zip`, no `transpose`, etc., so we get to roll our own. Big props to @DarthTwon for the 12-byte golf.

Takes input `$n`, sets up a `for` loop. Initialization sets `$x` to `0`, the test is whether we still have letters in our word `$n[0][$x]`, and we increment `$x++` each iteration.

Inside the loop, we take our array of strings, pipe it to an inner loop that spits out the appropriate character from each word. That is encapsulated in a `-join` to form a string, and that string is left on the pipeline. At end of execution, the strings on the pipeline are implicitly printed.

```
PS C:\Tools\Scripts\golfing> .\convert-n-strings.ps1 "Darth","-Twon","Rocks"
D-R
aTo
rwc
tok
hns

```
> 7 votes

# Answer
## CJam, ~~6~~ 5 bytes

*Saved 1 byte thanks to Luis Mendo.*

```
qS%zp

```

Try it online!

```
q      e# Get all input
 S%    e# Split it on spaces
   z   e# Take the transpose
    p  e# Print it as an array

```
> 5 votes

# Answer
## Retina, ~~45~~ 43 bytes

Byte count assumes ISO 8859-1 encoding.

```
O$#`.(?<=(.+))|¶
$.1
!`(?<=(¶)+.*)(?<-1>.)+

```

The leading linefeed is significant. Input and output are linefeed-terminated lists of printable ASCII strings (note that both have a single trailing linefeed).

Try it online!

I knew for a while that transposing rectangular blocks would be a pain in Retina (whereas transposing squares isn't too bad), but never actually tried. The first solution was indeed a whopping 110 bytes long, but after several substantial changes in the approach, the resulting 45 bytes are by far not as bad as I suspected (but still...). Explanation will follow tomorrow.

### Explanation

**Stage 1: Sort**

```
O$#`.(?<=(.+))|¶
$.1

```

This does the main work of reordering the characters in the input, but it ends up messing up the separation into lines. Interestingly, if we remove the , we get the code required to transpose a square input.

Sort stages (denoted by the `O`) work like this: they find all matches of the given regex (the thing after the ```), and then sort those matches and reinsert them into the places where the matches were found. As it happens, this regex matches every single character: non-linefeeds via the `.(?<=(.*))` alternative and linefeeds via the . Hence, it sorts all characters in the input. The more interesting part is what they are sorted *by*.

The `$` option activates a "sort-by" mode, where each match is replaced with the substitution pattern on the second line, which is then used for comparing the matches. Furthermore, the `#` tells Retina to convert the result of the substitution to an integer, and compare those integers (instead of treating them as strings).

So finally, we need to look at the regex and the substitution. If the first alternative matches (i.e. we have matched any character within one of the lines), then the `(?<=(.*))` captures everything up to that character on that line into group `1`. The `$.1` in the substitution pattern replaces this with the *length* of group `1`. Hence, the first character in each string becomes `1`, the second becomes `2`, the third becomes `3` and so on. It should be clear now how this transposes a square input: all the first characters of the lines come first and all end up in the top-most line, then all the second characters end up in the second line and so on. But for these rectangular inputs, we're also matching the linefeeds. Since group `1` is unused in this case, the substitution is empty, but for the purposes of the `#` option, this is considered `0`. That means, all the linefeeds are sorted to the front.

So now we do have the characters in the first order (first character of each string, second character of each string, etc.) and all the linefeeds at the start.

**Stage 2: Match**

```
!`(?<=(¶)+.*)(?<-1>.)+

```

We now need to split up the characters into lines of the correct length. This length corresponds to the number of lines in the original input, which is corresponds to the number of linefeeds we have at the beginning of the string.

The splitting is done here with the help of a match stage, which simply finds all matches of the given regex and uses the `!` option to print those matches (the default would be to count them instead). So the goal of the regex is to match one line at a time.

We start by "counting" the number with the lookbehind `(?<=(¶)*.*)`. It generates one capture in group `1` for every linefeed at the front.

Then, for each of those captures, we match a single character with `(?<-1>.)+`.
> 5 votes

# Answer
## Pyke, 1 byte

```
,

```

Try it here!

Transpose.
> 4 votes

# Answer
# x86 machine code, 19 bytes

In hex:

```
fc89d35651a401dee2fb91aa595e464a75f1c3

```

Input: `ECX`: # of strings (n), `EDX`: individual string length (m), `ESI`: array of input strings, `EDI`: output buffer receiving array of strings. Array is presumed to be defined as `char src[n][m+1]` for input and `char dst[m][n+1]` for output, and all strings are NULL-terminated.

```
0:  fc                  cld
1:  89 d3               mov ebx,edx   ;EDX is the counter for the outer loop
_outer:
3:  56                  push esi
4:  51                  push ecx
_inner:
5:  a4                  movsb         ;[EDI++]=[ESI++]
6:  01 de               add esi,ebx   ;Same char, next string
8:  e2 fb               loop _inner   ;--ECX==0 => break
a:  91                  xchg eax,ecx  ;EAX=0
b:  aa                  stosb         ;NULL-terminate just completed string
c:  59                  pop ecx
d:  5e                  pop esi       ;First string,
e:  46                  inc esi       ;...next char
f:  4a                  dec edx
10: 75 f1               jnz _outer
12: c3                  ret

```
> 4 votes

# Answer
# Brachylog, 5 bytes

```
z:ca.

```

Expects a list of strings as input, e.g. `run_from_atom('z:ca.',["money":"taken":"trust"],Output).`

### Explanation

```
z       Zip the strings in the Input list
 :ca.   output is the application of concatenation to each element of the zip

```
> 3 votes

# Answer
## 05AB1E, 3 bytes

```
ø€J

```

**Explained**

```
     # implicit input, eg: ['car', 'dog', 'man', 'yay']
ø    # zip, producing [['c', 'd', 'm', 'y'], ['a', 'o', 'a', 'a'], ['r', 'g', 'n', 'y']]
 €J  # map join, resulting in ['cdmy', 'aoaa', 'rgny']

```

Try it online
> 3 votes

# Answer
# JavaScript ES6, ~~48~~ 46 bytes

```
a=>[...a[0]].map((n,x)=>a.map(a=>a[x]).join``)

```

I feel left out, we have no built in zip function. Thanks nicael for pointing out my type error.

Usage

```
(a=>[...a[0]].map((n,x)=>a.map(a=>a[x])))(["asd","dsa"]); //or whatever is above, might change due to edits

```

returns

```
["ad","ss","da"]

```
> 2 votes

# Answer
# CJam, 3 bytes

```
{z}

```

This is a code block (equivalent to a function; allowed by default) that expects the input on the stack and leaves the output on the stack.

**Try it online!**
> 2 votes

# Answer
# Bash + BSD utilities, 27

```
sed s/./\&:/g|rs -c: -g0 -T

```

I/O via STDIN/STDOUT newline-separated strings.

You may need to install `rs` with `sudo apt install rs` or similar. Works out of the box on OS X.

The `-T` option to `rs` does the heavy lifting of the transposition. The rest is just formatting:

* The `sed` command simply inserts `:` after every character
* `-c:` specifies input columns are `:` separated
* `-g0` specifies output columns have zero width separation

If my reading of the `rs` manpage is correct, then the following **ought** to work for a score of 12, but unfortunately it doesn't work - see note below:

```
rs -E -g0 -T

```

### Example output:

```
$ printf "%s\n" car dog man yay |sed s/./\&:/g|rs -c: -g0 -T
cdmy
aoaa
rgny
$

```

If input is expected to be all printable ASCII, then the `:` may be replaced with some unprintable character, e.g. 0x7 `BEL`.

---

### Note

I wanted to understand why I couldn't get the `-E` option to work and get rid of the `sed` preprocessing. I found the `rs` source code here. As you can see, giving this option sets the `ONEPERCHAR` flag. However, there is nothing in the code that actually checks the state of this flag. So I think we can say that despite the fact that is option is documented, it is not implemented.

In fact, this option is documented in the Linux `rs` manpage:

> -E Consider each character of input as an array entry.

but not the OS X version.
> 2 votes

# Answer
# PHP, 82 bytes

```
function f($a){foreach($a as$s)foreach(str_split($s)as$i=>$c)$y[$i].=$c;return$y;}

```

takes and returns an array of strings

**break down**

```
function f($a)
{
    foreach($a as$s)                    // loop through array $a
        foreach(str_split($s)as$i=>$c)  // split string to array, loop through characters
            $y[$i].=$c;                 // append character to $i-th result string
    return$y;
}

```

**examples**

```
$samples=[
    ["asd","dsa"], ["ad","ss","da"],
    ["car", "dog", "man", "yay"], ["cdmy", "aoaa", "rgny"],
    ["money", "taken", "trust"], ["mtt", "oar", "nku", "ees", "ynt"]
];
echo '
';
while ($samples)
{
    echo 'in: ';         print_r($x=array_shift($samples));
    echo 'out: ';        print_r(f($x));
    echo 'expected: ';   print_r(array_shift($samples));
    echo '
';
}

```
> 2 votes

# Answer
## APL, 3 bytes

```
↓⍉↑

```

takes the input strings and turns them into a char matrix.  transposes the matrix.  splits back the rows of the resulting matrix into strings.
> 2 votes

# Answer
# K, 1 byte

```
+

```

Try it here!

Transpose
> 2 votes

# Answer
# MATLAB / Octave, 4 bytes

```
@(x)x'

```

This defines an anonymous function. Input format is `['car'; 'dog'; 'man'; 'yay']`.

**Try it here**.
> 1 votes

# Answer
# Mathematica, 26 bytes

```
""<>#&/@(Characters@#)&

```

Anonymous function. Takes a string list as input and returns a string list as output. The Unicode character is U+F3C7, representing `\[Transpose]`. Works by converting to a character matrix, transposing, and converting back to a string list. If the input/output format was stretched, then a simple 5-byte transpose would work:

```
#&

```
> 1 votes

# Answer
# Haskell, 41 bytes

```
f l=zipWith($)[map(!!n)|n<-[0..]]$l<$l!!0

```

Or with a bit more air:

```
f l = zipWith ($) [map (!! n) | n <- [0..]] $
                  l <$ (l !! 0)

```

The second list is the list of words repeated “the length of a word” time. On each list of words, we select the n-th letter of each word, giving the result.
> 1 votes

# Answer
## Common Lisp, 62 bytes

```
(lambda(s)(apply'map'list(lambda(&rest x)(coerce x'string))s))

```

The `map` function takes a result type (here `list`), a function *f* to apply and one or more sequences *s1*, ..., *sn*. All sequences are iterated in parallel. For each tuple of elements *(e1,...,en)* taken from those sequences, we call *(f e1 ... en)* and the result is accumulated in a sequence of the desired type.

We take a list of strings, say `("car" "dog" "man" "yay")`, and use `apply` to call `map`. We have to do this so that the input list is used as more arguments to `map`. More precisely, this:

```
(apply #'map 'list fn '("car" "dog" "man" "yay"))

```

... is equivalent to:

```
(map 'list f "car" "dog" "man" "yay")

```

And since strings are sequences, we iterate in parallel over all first characters, then all second characters, etc... For example, the first iteration calls *f* as follows:

```
(f #\c #\d #\m #\y)

```

The anonymous lambda takes the list of arguments given to it and coerces it back to a string.
> 1 votes

# Answer
## Perl, 91 bytes

So lengthy one..

```
$l=<>;$p=index($l," ")+1;@i=split//,$l;for$a(0..$p-1){print$i[$a+$_*$p]for(0..$p);print" "}

```

Try it here!
> 1 votes

# Answer
# Ruby, 40 bytes

```
->a{a.map(&:chars).transpose.map &:join}

```

Attempt This Online!
> 1 votes

# Answer
# J-uby, 24 bytes

Port of my Ruby answer.

```
:*&A|:transpose|:*&:join

```

Attempt This Online!

## Explanation

```
:* & A | :transpose | :* & :join

:* & A |                          # Map converting to character arrays, then
         :transpose |             # Transpose, then
                      :* & :join  # Map with join

```
> 1 votes

# Answer
# Go, 111 bytes

```
type S=[]string
func f(I S)S{O:=make(S,len(I[0]))
for _,s:=range I{for j,r:=range s{O[j]+=string(r)}}
return O}

```

Attempt This Online!
> 1 votes

# Answer
# Japt, 1 byte

Simply transposes the input.

```
Õ

```

Try it
> 1 votes

# Answer
# Ruby, 46 bytes

Probably the first time that "Ruby strings aren't Enumerables" is actually biting me hard since I had to map the strings into arrays before processing. (Normally having to use `String#chars` isn't enough of a byte loss to matter, but since I need to map them, it stings a lot more)

```
->s{s.map!(&:chars).shift.zip(*s).map &:join}

```
> 0 votes

# Answer
# Clojure, 68 bytes

```
#(map(fn[g](reduce(fn[a b](str a(nth b g)))""%))(range(count(% 0))))

```

Maps a function which is just `reduce` (goes on elements of the list one by one and joins nth character of the string) on the range from 0 to length of the first string.

See it online: https://ideone.com/pwhZ8e
> 0 votes

# Answer
# C#, 53 bytes

```
t=>t[0].Select((_,i)=>t.Aggregate("",(a,b)=>a+b[i]));

```

C# lambda (`Func`) where the output is `IList<string>` and the output is `IEnumerable<string>`. I dont know how work `zip` in other language but I can't find a way to use the C#'s one here. `Aggregate` fit the need well. No transpose in C#, there is one in Excel but I wont use it.

Try it online!
> 0 votes

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


title: Calculate golden ratio

text:
# Question
Title: Calculate golden ratio
Write the shortest code, in number of bytes, to display, return, or evaluate to the golden ratio (that is, the positive root of the quadratic equation: \\$x^2-x-1=0\\$, approximately 1.618033988749895), to at least 15 significant figures. No input will be given to your program.

Sample in Stutsk programming language:

```
1 100 { 1 + 1 swp / } repeat print

```

# Answer
## Perl, Python - 10 chars

probably other languages too

```
.5+5**.5/2

```
> 19 votes

# Answer
# Julia 0.7, 2 bytes

```
φ

```

Try it online!

I'm surprised nobody has posted this yet...
> 10 votes

# Answer
# Mathematica 11

```
GoldenRatio

```

This is the irrational number itself, not an approximation of it.

**Examples** (first 2 examples from Mathematica documentation)

```
FullSimplify[GoldenRatio^4 - GoldenRatio]
FullSimplify[GoldenRatio^20 + 1/GoldenRatio^20]
FullSimplify[GoldenRatio^2 - GoldenRatio - 1]

```

> 3 + Sqrt\[5\]
>
> 15127
>
> 0
> 8 votes

# Answer
# Desmos, 8 bytes

```
aa-a~1
a

```

Try it on Desmos!
> 8 votes

# Answer
**PHP 17 chars**

This one is just trolling, but hey.

```
1.618033988749895

```
> 7 votes

# Answer
# k (10 chars)

As continued fraction:

```
{%x%x+1}/1

```

Or in closed form for 11:

```
%2%1+sqrt 5

```
> 6 votes

# Answer
# J, 7 chars

```
-:1+%:5

```

some more text for the filter (my first J solution, heh)
> 6 votes

# Answer
# APL, 7

```
2÷⍨1+√5
÷2÷1+√5
.5×1+√5
.5+√5÷4

```

Curses! I can't find a way to do it in less than 7 characters! Dialect is Nars2000.
> 6 votes

# Answer
## JavaScript (ECMAScript), 10 chars

```
5**.5/2+.5

```

This is the same as the Perl & Python submission - thanks to **Redwolf Programs** for telling me about this.

However, back in 2012, when this answer was originally written, the `**` operator did not exist in JavaScript. While almost all browsers and do now support the exponentiation operator, according to Can I Use, as of July 2020, around 9% of users still does not support it, including the latest version of Internet Explorer. Thus, the old version of the answer:

**JavaScript (backwards-compatible), 17 chars**

```
Math.sqrt(5)/2+.5

```
> 4 votes

# Answer
# Language Agnostic, 15 chars

```
9227465/5702887

```

If all you need is enough precision for an IEEE 32 bit float, you can do it in 9 chars:

```
6765/4181

```

This will only work for languages that don't treat integer division specially.
> 3 votes

# Answer
# dc, 8 chars

```
Fk5v1+2/

```

The value is on top of the stack - can be printed by adding `p` to the end of the program. `F` pushes 15 on the stack (trick found here), `k` sets the precision to 15 digits. The rest is normal postfix notation :-) `v` is a square root. Trailing `p` for print was omitted.
> 3 votes

# Answer
**J, 10 9 8 chars**

```
p.1,1,_1

```

(root of polynomial: -x^2+x+1)

```
>:@%^:_+1

```

(continued fraction (9 chars))

```
%:@>:^:_+1

```

(continued root: (10 chars))
> 3 votes

# Answer
# 05AB1E, 6 bytes

```
5X‚t;O

```

Try it online!

# Explanation

```
5      Push 5
 X     Push 1
  ‚    Pair: [5, 1]
   t   Square root: [2.23606797749979, 1.0]
    ;  Halve: [1.118033988749895, 0.5]
     O Sum: 1.618033988749895

```
> 3 votes

# Answer
# Arn, 3 bytes

```
phi

```

Just a builtin, too short to be compressed. Returns `1.61803398874989484820458683436563811`.

A more interesting one. If running in the downloadable version, this will print `n` digits, given the command:

```
arn run file.arn -p n

```

or 25 digits if the `-p` flag is not provided.

If running in the online version, this will print the first 50 digits.

## 6 bytes

```
l[├Qn0

```

Try it!

### Explanation

Unpacked: `:-1+:/5`

```
:-       Halve
    1    Literal one
  +      Plus
    :/   Square root of
      5  Literal five

```
> 3 votes

# Answer
# Husk, 4 bytes

**(floating-point; accurate to 15 significant figures)**

```
½→√5

```

Try it online!

This seems (to me) to be surprisingly readable for a golfing language...

```
  √5    # square root of 5
 →      # increment
½       # halve

```

---

# Husk, 9 bytes

**(calculation as arbitrary precision rational number)**

```
!Ẋ/İf!5İ⁰

```

Try it online! (TIO header converts the rational number \[expressed in Husk as a fraction\] to its first 1000 decimal digits)

```
  /         # get the ratio of
 Ẋ          # every pair of elements of
   İf       # the fibonacci sequence;
!           # now select the ratio at position
     !5İ⁰   # 10^5 (change to !9İ⁰ for more accuracy with same byte-count)

```
> 3 votes

# Answer
# Malbolge, 102 bytes

```
(C%;_#!7[}{3Wyw/St,+0/(-&Jlk"FEg|{A?~,`<^:r[Y64m3kT0Rg,xwc;J`&%#5"!~Bji.-,X;POsMppn"2GFEiCg+e?>b<;_#![

```

Try it online!
> 3 votes

# Answer
# brainf, 93 bytes

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

```

Try it online!

It works :/ Not very optimised though. I can’t think of any way to optimize this, although I’m sure a way exists.

Explanation:

```
+++++++         Add seven to cell at 0.
[               Begin a loop.
     >+++++++   Add seven to cell at 1.
     <          Go back to cell 0.
     -          Decrement the counter there (soon it will reach 0).
]               End loop when cell 0 reaches 0 after 7 repetitions.
>               Go to cell 1 which is now 49.
.               Print it (1).
---.            Decrement 3 to get 46 (period) then print it.

Afterwards, not much explanation is needed. Just add some
or subtract some and repeat until everything is printed.
++++++++.-----.+++++++.--------.+++..++++++.-..-.---.+++++.-.+.----.

```
> 3 votes

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

```
(1+1%)/1

```

Try it online!

Adapted from the built-in docs.

* `(...)/1` set up a converge-reduce, seeded with 1 and run until two successive iterations return the same result
    + `(1+1%)` add one to the inverse of the current value, and feed that into the next iteration
> 3 votes

# Answer
# Ruby - 14 chars

```
(5**0.5)/2+0.5

```

Based on the Javascript Perl answer above.
> 2 votes

# Answer
# Almost language agnostic, 9 chars

### (tested in R):

```
.5+5^.5/2

```

In R, evaluates full double precision. More digits can be seen by setting `options(digits=99)`. The question says "evaluate", so that goes with the rules.
> 2 votes

# Answer
# x86 machine code, 13 bytes

Hexdump:

```
b1 7f d9 e8 d9 e8 de c1 d9 fa e2 f8 c3

```

Disassembly:

```
100139D0 B1 7F                mov         cl,7Fh
100139D2 D9 E8                fld1
    again:
100139D4 D9 E8                fld1
100139D6 DE C1                faddp       st(1),st
100139D8 D9 FA                fsqrt
100139DA E2 F8                loop        again (100139D4h)
100139DC C3                   ret

```

Uses the converging sequence `a<sub>n</sub> = sqrt(a<sub>n-1</sub> + 1)`.

The number of iterations is determined by the contents of `ecx`, which is mostly garbage. The minimal number of iterations is 127, which guarantees good precision (actually, 30 iterations should be enough). In the worst case, the calculation will take a few minutes (232-1 iterations), and in the best case, it's instantaneous (127 iterations).
> 2 votes

# Answer
## Python 3, 11 bytes

```
(1+5**.5)/2

```

= 1.618033988749895
> 2 votes

# Answer
# Whispers v3, 16 bytes

```
> φ
>> Output 1

```

Try it online!
> 2 votes

# Answer
# \>\<\>, ~~29~~, 25 bytes

Saved **4 bytes**!

After posting this answer I noticed the example Stutsk program and realized that I could probably save a few bytes. My new answer is based off the example given in the question. This program works because the golden ration can be expressed as a continued fraction.

`golden_ratio = 1+1/(1+1/(1+1/...))`

```
ff*101.;n~<
$1$,1+$:?!^1-

```

Try it online!

## Old Answer

```
f201.;n,2+1~<
$:5$,+2,$:?!^1-

```

The second line approximates the sqrt of 5. After looping 15 times, this value is used to calculate the golden ratio.

Try it online!
> 2 votes

# Answer
# Pyth, 3 bytes

```
.n3

```

Try it online!

11 bytes without builtin:

```
+c@5 2 2 .5

```

Try it online!
> 2 votes

# Answer
# dc - 11 chars

```
15k5v2/.5+p

```

The most character-consuming task is setting the decimal precision..
> 1 votes

# Answer
# Mathematica - 31

```
N[x/.Solve[x^2-x-1==0][[2]],16]

1.618033988749895

```

(It's going to be the longest code, I expect...:)
> 1 votes

# Answer
# Japt, 2 bytes

```
MQ

```

Test it

Or 6 bytes without the built-in:

```
½+5¬/2

```

Test it
> 1 votes

# Answer
# MathGolf, 1 byte

```
φ

```

Builtins ftw ¯\\\_(ツ)\_/¯

Try it online.

**Without builtins it's 6 bytes:**

```
51α√½Σ

```

Try it online.

**Explanation:**

```
φ       # Push golden ratio builtin 1.618033988749895
        # (output the entire stack joined together implicitly as result)

5       # Push 5
 1      # Push 1
  α     # Wrap the last two values into a list: [5,1]
   √    # Take the square-root of each value: [2.23606797749979,1.0]
    ½   # Halve each: [1.118033988749895,0.5]
     Σ  # And sum this list: 1.618033988749895
        # (after which the entire stack joined together is output implicitly as result)

```
> 1 votes

# Answer
# CJam, 7 bytes

```
X5mq+2/

```

Try it online

Just one more byte than 05AB1E! Pretty simple stack-based translation of the equation on the Wikipedia page:

```
X5         Push 1 and 5 on to the stack
  mq       Square root the top number
    +      Add the top two numbers on the stack
     2/    Divide by two
           (implicit) output the stack

```
> 1 votes

# Answer
# MUMPS, 11 bytes

```
w 5**.5+1/2

```

Output: `1.618033988749894849`

This highlights a quick about MUMPS: order of operations is evaluated left to right. Something like `.5+5**.5/2` would give us `(5.5**.5)/2` (`1.172603939955857389`).
> 1 votes

# Answer
# 05AB1E, 4 bytes

```
5t>;

```

Try it online!

```
5t>;  # full program
   ;  # divide...
 t    # square root of...
5     # literal...
  >   # plus 1...
   ;  # by 2
      # implicit output

```
> 1 votes

# Answer
# Gol\>\<\>, 4 bytes

```
S1n;

```

This answer feels like cheating because `S1` simply pushes the golden ratio onto the stack.

This answer doesn't work with TIO, but it does work with this interpreter: Try it online!
> 1 votes

# Answer
# Tcl, 23 bytes

```
puts [expr (1+5**.5)/2]

```

Try it online!
> 1 votes

# Answer
# Pip, 6 bytes

```
URT5/2

```

Replit! Or, here's a 7-byte equivalent in Pip Classic: Try it online!

### Explanation

```
 RT5    Square root of 5
U       Increment
    /2  Divide by 2

```
> 1 votes

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

```
φ .

```

Try it online!
> 1 votes

# Answer
# Rattle, 8 bytes

```
=5e.5+/p

```

Try it Online!

# Explanation

```
=5          set top of stack to 5
  e.5       square root
     +      increment
      /     divide by 2
       p    print value

```

This first approach is pretty boring, it's just a direct calculation. Here's a slightly more exciting 13-byte method which calculates many Fibonacci numbers then finds the ratio between them:

```
+s[+~$]99$/~p

```

Try it Online!

# Explanation

```
+s              increment the top of the stack (to 1) and save to memory
  [   ]99       loop 99 times
   +~           increment top of stack by the value in memory
     $          swap the top of the stack for the value in memory
         $      swap the top of the stack for the value in memory
          /~    divide the top of the stack by the value in memory
            p   print value

```
> 1 votes

# Answer
# Vyxal , 2 bytes

```
kg

```

Try it Online!
> 1 votes

# Answer
# Python, 33 bytes

```
ratio=(1+5**(1/2))/2
print(ratio)

```

Output:

```
1.618033988749895

```
> 0 votes

# Answer
# C (gcc), 37 bytes

Very basic solution, calculates exact value & prints.

```
main(){printf("%.15f",.5+sqrt(5)/2);}

```

Try it online!
> 0 votes

# Answer
# Jelly, 2 bytes

```
Øp

```

Try it online!
> 0 votes

# Answer
# POSIX bc, 13+2(?)=15(?) bytes

bc forbids non-integer exponents, so:

```
.5+sqrt(5/4)

```

(incl. the newline) *plus* `-l` for the math library (which also conveniently bumps the scale); therefore:

```
$ echo '.5+sqrt(5)/2' | bc -l
1.61803398874989484820

```
> 0 votes

---
Tags: code-golf, math, kolmogorov-complexity
---