title: Find all \$k\$-smooth pairs

text:
# Question
Title: Find all \$k\$-smooth pairs
### Introduction

In number theory, we say a number is \\$k\\$-smooth when its prime factors are all at most \\$k\\$. For example, 2940 is 7-smooth because \\$2940=2^2\cdot3\cdot5\cdot7^2\\$.

Here, we define a \\$k\\$-smooth pair as two consecutive integers which both are \\$k\\$-smooth. An example of 7-smooth pair will be \\$(4374,4375)\\$ because \\$4374=2\cdot3^7\\$ and \\$4375=5^4\cdot7\\$. **Fun fact: This is actually the largest 7-smooth pair**.

Størmer proved in 1897 that for every \\$k\\$, there are only finitely many \\$k\\$-smooth pairs, and this fact is known as **Størmer's Theorem**.

### Challenge

Your task is to write a program or function that, given a prime number input \\$k\\$, outputs or returns all \\$k\\$-smooth pairs without duplicate (order within the pair does not matter) in any order you want.

Please be noted that for prime numbers \\$p\\$ and \\$q\\$, assuming \\$p\<q\\$, all \\$p\\$-smooth pairs are also \\$q\\$-smooth pairs.

### Sample I/O

```
Input: 2
Output: (1, 2)

Input: 3
Output: (1, 2), (2, 3), (3, 4), (8, 9)

Input: 5
Output: (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (8, 9), (9, 10), (15, 16), (24, 25), (80, 81)

Input: 7
Output: (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10), (14, 15),
        (15, 16), (20, 21), (24, 25), (27, 28), (35, 36), (48, 49), (49, 50), (63, 64),
        (80, 81), (125, 126), (224, 225), (2400, 2401), (4374, 4375)

```

### Restriction

The program or function should theoretically terminate in finite time for all inputs. Standard loopholes are disallowed by default.

### Winning Criteria

As this is a challenge, shortest valid submission for each language wins.

# Answer
> 10 votes
# JavaScript (ES7),  ~~234~~  232 bytes

Finds the solutions by solving Pell equations of the form \\$x^2-2qy^2=1\\$, where \\$q\\$ is a \\$P\\$-smooth square free number.

This is an implementation of Derrick Henry Lehmer's procedure, derived from Størmer's original procedure.

Returns an object whose keys and values describe the \\$P\\$-smooth pairs.

```
P=>[...Array(P**P)].map((_,n)=>(s=(n,i=0,k=2)=>k>P?n<2:n%k?s(n,i,k+1):s(n/k,i,k+i))(n,1)&&(_=>{for(x=1;(y=((++x*x-1)/n)**.5)%1;);(h=(x,y)=>k--&&h(X*x+n*Y*y,X*y+Y*x,x&s(x=~-x/2)&s(x+1)?r[x]=x+1:0))(X=x,Y=y,k=P<5?3:-~P/2)})(),r={})&&r

```

Try it online!

### How?

The helper function \\$s\\$ tests whether a given integer \\$n\\$ is a \\$P\\$-smooth number when it's called with \\$i=0\\$, or a square free1 \\$P\\$-smooth number when it's called with \\$i=1\\$.

```
s = (
  n,
  i = 0,
  k = 2
) =>
  k > P ?
    n < 2
  :
    n % k ?
      s(n, i, k + 1)
    :
      s(n / k, i, k + i)

```

We look for all square free1 \\$P\\$-smooth numbers in \\$\[1..P^P-1\]\\$, where \\$P^P\\$ is used as an upper bound for \\$P!\\$.

```
P=>[...Array(P ** P)].map((_, n) => s(n, 1) && (...))

```

For each number \\$n\\$ found above, we look for the fundamental solution of the Pell equation \\$x^2-ny^2=1\\$:

```
(_ => {
  for(x = 1; (y = ((++x * x - 1) / n) ** .5) % 1;);
  ...
})()

```

(the above code is the non-recursive version of my answer to this other challenge)

Once the fundamental solution \\$(x\_1,y\_1)\\$ has been found, we compute the solutions \\$(x\_k,y\_k)\\$ with \\$k\le max(3,(P+1)/2)\\$, using the recurrence relations:

$$x\_{k+1}=x\_1x\_k+ny\_1y\_k\\ y\_{k+1}=x\_1y\_k+y\_1x\_k $$

For each \\$x\_k\\$, we test whether \\$x\_k\\$ is odd and both \\$(x\_k-1)/2\\$ and \\$(x\_k+1)/2\\$ are \\$P\\$-smooth. If so, we store them in the object \\$r\\$.

```
( h = (x, y) =>
  k-- &&
  h(
    X * x + n * Y * y,
    X * y + Y * x,
    x &
    s(x = ~-x / 2) &
    s(x + 1) ?
      r[x] = x + 1
    :
      0
  )
)(X = x, Y = y, k = P < 5 ? 3 : -~P / 2)

```

---

*1: Because it does not test the primality of the divisors, the function \\$s\\$ will actually be truthy for some non-square free numbers, even when it's called with \\$i=1\\$. The idea is to filter out most of them so that not too many useless Pell equations are solved.*

# Answer
> 4 votes
# Jelly, ~~16~~ 14 bytes

```
4*ÆfṀ<ɗƇ‘rƝLÐṂ

```

Try it online!

Checks for pairs up to \\$4^k\\$ which is inefficient for larger \\$k\\$ but should ensure none are missed.

Thanks to @JonathanAllan for saving 1 byte!

### Explanation

```
4*ÆfṀ<ɗƇ‘rƝLÐṂ  | Monadic link, input k

4*              | 4**k, call this n
      ɗƇ        | For each number from 1..n filter those where:
  Æf            |   - Prime factors
    Ṁ           |   - Maximum
     <  ‘       |   - Less than k+1
         rƝ     | Inclusive range between neighbouring values
           LÐṂ  | Keep only those of minimum length (i.e. adjacent values)

```

# Answer
> 3 votes
# 05AB1E, 8 bytes

```
°Lü‚ʒfà@

```

Try it online!

Explanation:

```
°            # 10 ** the input
 Lü‚         # list of pairs up to that number
    ʒ        # filtered by...
     fà      # the greatest prime factor (of either element of the pair)...
       @     # is <= the input

```

# Answer
> 2 votes
# Haskell, ~~118~~ 107 bytes

-11 bytes thanks to nimi

```
q 1=[1]
q n=(:)<*>q.div n$[x|x<-[2..n],mod n x==0]!!0
f k|let r=all(<=k).q=[(n,n+1)|n<-[1..4^k],r n,r(n+1)]

```

Try it online!

* `q n` calculates a list of all prime factors of `n`
* `f k` generates a list of \\$k\\$-smooth pairs for a given k by filtering a list of all pairs

# Answer
> 2 votes
# Jelly, 123 bytes

```
¹©Æ½Ø.;µU×_ƭ/;²®_$÷2ị$}ʋ¥⁸;+®Æ½W¤:/$$µƬṪ€F¹;Ḋ$LḂ$?ṭ@ṫ-ṚZæ.ʋ¥ƒØ.,U¤-ịWµ1ịżU×®W¤Ɗ$æ.0ị$ṭµ³’H»3¤¡
ÆRŒPP€ḟ2ḤÇ€ẎḢ€+€Ø-HÆfṀ€<ẠʋƇ‘

```

Try it online!

This is a relatively efficient but long Jelly answer that uses the continued fractions method to solve the fundamental solution for the Pell equations for \\$2×\\$ each k-smooth square-free number, finds \\$\max(3, \frac{k+1}{2})\\$ solutions for each and then checks whether \\$\frac{x-1}{2}, \frac{x+1}{2}\\$ are smooth for each solution. This is Lehmer’s method, as described in the question’s Wikipedia link.

A full program that takes a single argument, \\$k\\$ and returns a list of lists of pairs. The code above doesn’t sort the final output, but the TIO link does.

# Answer
> 1 votes
# Jelly, 24 bytes

```
³!²R‘Ė
ÇÆFḢ€€€’<³FȦ$€Tị¢

```

Try it online!

This takes a long time for 7, but it computes much faster if you remove the squaring of the factorial: Try it online!

**Explanation:**

```
³!²R‘Ė                Generates a list like [[1,2],[2,3],...]
³!²                  Take the square of the factorial of the input
   R                 Range 1 through through the above number.
    ‘Ė               Decrement and enumerate, yielding desired list

ÇÆFḢ€€€’<³FȦ$€Tị¢
Ç                    Get the list of pairs
 ÆF                  Get the prime factors of each number
   Ḣ€€€              Get the base of each
       ’<³           Is each base less than or equal to the input?
          FȦ$€       Check that all bases of a pair fit the above.
              T      Get a list of the truthy indexes
               ị¢    Index into the original list of pairs
                     Implicit output

```

-3 bytes thanks to @JonathanAllen

# Answer
> 1 votes
# Wolfram Language (Mathematica), 241 bytes

uses Pell equations

```
(s=#;v@a_:=Max[#&@@@#&/@FactorInteger@a]<=s;Select[{#-1,#+1}/2&/@(t={};k=y=1;While[k<=Max[3,(s+1)/2],If[IntegerQ[x=Sqrt[1+2y^2#]],t~AppendTo~x;k++];y++];t),v@#&]&/@Join[{1},Select[Range[3,Times@@Prime@Range@PrimePi@s],SquareFreeQ@#&&v@#&]])&

```

Try it online!

# Answer
> 1 votes
# Python 3 \+ sympy, 116 bytes

```
import sympy
def f(k):x=[i for i in range(2,4**k)if max(sympy.factorint(i))<=k];return[(y,y+1)for y in x if y+1in x]

```

Try it online!

# Python 3 \+ sympy, 111 bytes

```
from sympy import*
def f(k):
 b=1
 for i in range(2,4**k):
  x=max(factorint(i))<=k
  if x&b:print(i-1,i)
  b=x

```

Try it online!

Two variations on my Jelly answer but in Python 3. They both define a function which accepts an argument `k`. The first returns a list of tuples of the pairs that meet the criteria. The second prints them to stdout.

# Answer
> 1 votes
# Pyth, 15 bytes

```
f!>#QsPMTCtBS^4

```

Try it online!

Uses Nick Kennedy's observation that no output number will be larger than `4^k`.

# Answer
> 1 votes
# 05AB1E, 16 bytes

```
°LʒfàI>‹}Xšü‚ʒ¥`

```

Try it online (extremely inefficient, so times out for \\$n\gt3\\$..). Here a slightly faster alternative, although still pretty slow..

**Explanation:**

```
°                # Take 10 to the power of the (implicit) input
 L               # Create a list in the range [1, 10^input]
  ʒ              # Filter this list by:
   fà            #  Get the maximum prime factor
     I>‹         #  And check if it's smaller than or equal to the input
        }Xš      # After the filter: prepend 1 again
           ü‚    # Create pairs
             ʒ   # And filter these pairs by:
              ¥` #  Where the forward difference / delta is 1

```

# Answer
> 0 votes
# Stax, 14 bytes

```
Θ",²aÇu,á‼⌐çLB

```

Run and debug it

This is not the shortest possible program, but it begins producing output as soon as matching pairs are found. It does terminate *eventually*, but output is produced as it's found.

# Answer
> 0 votes
# Ruby, 89+8 = 97 bytes

Uses the `-rprime` flag. For each number \\$i\\$ from 1 to \\$4^n\\$, map it to `[i, i+1]` if both are \\$n\\$-smooth, otherwise map it to `false`, then prune all `false` from the list.

```
->n{g=->x{x.prime_division.all?{|b,_|b<=n}};(1..4**n).map{|i|g[i]&&g[i+1]&&[i,i+1]}-[!1]}

```

Try it online!

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


title: Golf my Ada arrays

text:
# Question
Title: Golf my Ada arrays
## Background

Ada is a programming language that is not exactly known for its terseness.

However, its array literal syntax can in theory allow for fairly terse array specifications. Here is a simple EBNF description of the array literal syntax (passable to bottlecaps.de:

```
array ::= positional_array | named_array
positional_array ::= expression ',' expression (',' expression)*
                   | expression (',' expression)* ',' 'others' '=>' expression
named_array ::= component_association (',' component_association)*
component_association ::= discrete_choice_list '=>' expression
discrete_choice_list ::= discrete_choice ('|' discrete_choice)*
discrete_choice ::= expression ('..' expression)? | 'others'

```

We will limit ourselves to 1-dimensional arrays of integers for simplicity. This means that we will use only integers for the expression values. Perhaps in a future challenge we could try something more advanced (like declaring variables and multidimensional arrays). *You do **not** have to golf the integer literals*.

Here are some examples of Ada array literals and a python-esque equivalent representation for clarity:

```
(1, 2, 3) = [1, 2, 3]
(1, others => 2) = [1, 2, 2, ..., 2]
(others => 1) = [1, 1, ..., 1]
(1 => 1, 2 => 3) = [1, 3]
(1|2 => 1, 3 => 2) = [1, 1, 2]
(1 => 1, 3 => 2, others => 3) = [1, 3, 2, 3, 3, ..., 3]

```

## Challenge

The goal of this challenge is to output the shortest byte-count Ada array literal for a given input array. Note that Ada arrays can start from whatever index is desired, so you can pick what you wish the starting index to be as long as each value is sequential. In this example I choose to start at 1, which is idiomatic for Ada, however you can choose to start at any other integer.

### Input

Your input will consist of a list of integers, in whatever form is convenient.

### Output

Your output will be a string of text representing the shortest valid Ada array literal that represents the list of input integers. You may use any starting index you wish on this array, but your choice (whatever it is) must be specified in your answer (the starting index may also be dynamic).

The integers are to represented as signed decimal numbers, as in the examples. This challenge does not cover golfing of integer values.

### Examples

Here are some examples:

```
Simple: [1, 2, 3] -> (1,2,3)
Range: [1, 1, 1, 1, 1, 1, 1,] -> (1..7=>1)
Others: [1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1] -> (6=>2,others=>1)
Multiple Ranges: [1,1,1,1,1,2,2,2,2,2,1,1,1,1,1,2,2,2,2,2,1,1,1,1,1] -> (6..10|16..20=>2,others=>1)
Tiny Ranges: [1,1,2,2,1,1,1,1,1] -> (3|4=>2,others=>1)
Far Range: [[1]*5, [2]*100, [3]*5] -> (1..5=>1,6..105=>2,others=>3)
Alternation: [1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2] -> (1|3|5|7|9|11|13|15|17=>1,others=>2)
Big Number: [1234567890,1,1234567890] -> (2=>1,1|3=>1234567890)
Big-ish Number: [1234567,1,1234567] -> (1234567,1,1234567)
Solo: [-1] -> (1=>-1)
Huge Input: [[0],[1]*1000000000] -> (0,others=>1)
Positional Others: [1, 2, 3, 3, 3, 3, 3, 3] -> (1,2,others=>3)
Range and Choice, no Others: [1,1,1,12,12,3,3,3,3,3,3,3,3,3,3,4] -> (1..3=>1,4|5=>12,6..15=>3,16=>4)

```

## Minimum Requirements

* Support at least 100 numbers and inputs of at least 256 numbers in length.
* Produce the correct result for all such inputs

+ Includes putting 'others' at the end
    + Includes putting an index for single item arrays
* Terminate (preferably on TIO) for each of the above inputs in under a minute.

Shortest solution in bytes wins!

## Reference Implementation

Try it online!

This implementation uses the input as its array, with each character being a number. Capital letters are special constants for large values. The program argument is the 'start index' to use.

The "code" section in the TIO link is a correct solution to the problem, while the "header" and "footer" implement the test structure.

# Answer
> 5 votes
# JavaScript (ES6),  ~~307~~  304 bytes

*Saved 2 bytes thanks to @KevinCruijssen*

This is embarrassingly long ...

```
a=>[b=([...a,m=''].map(o=(v,i)=>(i?p==v?!++n:m=o[(o[p]=[o[p]&&o[p]+'|']+(n?i-n+(n>1?'..':'|')+i:i))[m.length]?(x=i-n,j=p):j]:1)&&(p=v,M=n=0)),Object.keys(o).map(k=>j-k|!m[6]?o[k]+'=>'+k:O,O='others=>'+j).sort()),1/a[1]?[...a]:b,j-a.pop()?b:a.slice(0,x-1)+[,O]].map(a=>M=M[(s=`(${a})`).length]||!M?s:M)&&M

```

Try it online!

# Answer
> 2 votes
# 05AB1E, ~~136~~ ~~134~~ 132 bytes

```
"',ý'(ì')«ˆ"©.V"θ…ˆ†=>ìª®.V"Uγ¨D€gPi˜IX.V}\ÙεQƶ0KDāαγ€g£}D2Fε¾iεнyg≠iyθyg<i'|ë„..}ý}}ë˜}'|ý„=>«Iyнн<è«}Ð®.VgFDN._ć'>¡X.V}\¼}¯éIgi¦}н

```

*EDIT: Fixed for all test cases now.*

Try it online or verify all test cases (except for the 'Huge Input' one, since it's too big).

**Explanation:**

```
"',ý'(ì')«ˆ"       # Push this string (function 1), which does:
 ',ý              '#  Join a list by ","
    '(ì           '#  Prepend a "("
       ')«        '#  Append a ")"
          ˆ        #  Pop and add it to the global array
            ©      # Store this string in the register (without popping)
             .V    # And execute it as 05AB1E code on the (implicit) input-list
"θ…ˆ†=>ìª®.V"      # Push this string (function 2), which does:
 θ                 #  Pop and push the last element of the list
  …ˆ†=>ì           #  Prepend dictionary string "others=>"
        ª          #  Append that to the list which is at the top of the stack
         ®.V       #  And execute function 1 from the register
             U     # Pop and store this string in variable `X`
γ                  # Get the chunks of equal elements in the (implicit) input-list
 ¨                 # Remove the last chunk
  D                # Duplicate the list of remaining chunks
   €g              # Get the length of each
     Pi     }      # If all chunk-lengths are 1:
       ˜           #  Flatten the list of remaining chunks
        I          #  Push the input-list
         X.V       #  Execute function 2 from variable `X`
             \     # Discard the top of the stack (in case we didn't enter the if-statement)
Ù                  # Uniquify the (implicit) input-list
 ε                 # Map each unique value `y` to:
  Q                #  Check for each value in the (implicit) input-list if it's equal to `y`
                   #  (1 if truthy; 0 if falsey)
   ƶ               #  Multiply each by its 1-based index
    0K             #  Remove all 0s
      D            #  Duplicate it
       ā           #  Push a list [1, length] without popping the list itself
        α          #  Get the absolute difference at the same indices
         γ         #  Split it into chunks of the same values
          €g       #  Get the length of each
            £      #  And split the duplicated indices-list into those parts
                   # (this map basically groups 1-based indices per value.
                   #  i.e. input [1,1,2,1,1,2,2,1,1] becomes [[[1,2],[4,5],[8,9]],[[3],[6,7]]])
 }D                # After the map: duplicate the mapped 3D list
   2F              # Loop 2 times:
     ε             #  Map the 3D list of indices to:
      ¾i           #   If the counter_variable is 1:
        ε          #    Map each list `y` in the 2D inner list to:
         н         #     Leave the first value
         yg≠i      #     And if there is more than one index:
             yθ    #      Push the last value as well
             yg<i  #      If there are exactly two indices:
              '|  '#       Push string "|"
             ë     #      Else (there are more than two indices)
              „..  #       Push string ".."
             }ý    #      And join the first and last value by this string
        }}         #    Close the if-statement and map
      ë            #   Else:
       ˜           #    Flatten the 2D list
      }'|ý        '#   After the if-else: join by "|"
          „=>«     #   Append "=>"
       yнн         #   Get the very first index of this 2D list
          <        #   Decrease it by 1 to make it 0-based
      I    è       #   And index it into the input-list to get its value again
            «      #   Which is also appended after the "=>"
     }Ð            #  After the map: triplicate the result
       ®.V         #  Execute function 1 from the register
       g           #  Get the amount of items in the triplicated list
        F          #  Loop that many times:
         D         #   Duplicate the list
          N._      #   Rotate it the index amount of times
          ć        #   Extract the head; pop and push remainder and head
           '>¡    '#   Split this head by ">"
              X.V  #   And then function 2 is executed again from variable `X`
        }\         #  After the loop: discard the list that is still on the stack
          ¼        #  And increase the counter_variable by 1
   }¯              # After looping twice: push the global array
     é             # Sort it by length
      Igi }        # If the input only contained a single item:
         ¦         #  Remove the very first item
           н       # And then only leave the first item
                   # (which is output implicitly as result)

```

See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*) to understand why `…ˆ†=>` is `"others=>"`.

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


title: Ambassadors and Translators

text:
# Question
Title: Ambassadors and Translators
Two ambassadors at a UN conference want to speak to each other, but unfortunately each one only speaks one language- and they're not the same language. Fortunately, they have access to several translators, who each understand and speak a few languages. Your task is to determine the shortest chain of translators (since you want as little to be lost in translation as possible) that allows the two ambassadors to speak with each other.

## Coding

**Input:** two languages as 2-letter lowercase strings (each ambassador's language) and a list of lists of languages (one list per available translator)

You may alternatively take in integers instead of 2-letter codes.

**Output:** A sequence of translators either by index or value that is any one of the shortest chains of translators that allows the two ambassadors to communicate. If there is no valid chain of translators, the behavior is undefined. (You may crash, output any arbitrary value, or indicate an error)

A valid chain of translators is one where the first translator speaks one ambassador's language, the second and subsequent translators share at least one language with the previous translator, and the last translator speaks the other ambassador's language.

## Examples

Using zero-based indexing:

```
es, en, [
    [es, en]
] ==> [0]

en, en, [] ==> []

en, jp, [
    [en, zh, ko, de],
    [jp, ko]
] ==> [0, 1]

es, ru, [
    [gu, en, py],
    [po, py, ru],
    [po, es]
] ==> [2, 1]

fr, gu, [
    [it, fr, de, es, po, jp],
    [en, ru, zh, ko],
    [jp, th, en],
    [th, gu]
] ==> [0, 2, 3]

fr, ru, [
    [fr, en],
    [en, ko, jp],
    [en, ru]
] ==> [0, 2]

de, jp, [
    [en, fr],
    [ko, jp, zh],
    [fr, po],
    [es, ko, zh],
    [de, en, th],
    [en, es],
    [de, fr]
] ==> [4, 5, 3, 1]

```

## Rules and Assumptions

* Standard IO rules (use any convenient I/O format) and banned loopholes apply.
* You may assume that speaking and understanding languages is perfectly symmetric and that all possible translations between languages are equally efficient.
* There is no concept of "close enough" languages. It is not good enough to use Portuguese on one end where Spanish is required, for instance.
* If there are multiple shortest translator chains, any one of them will do.
* If the ambassadors happen to speak the same language, the translator list should be empty
* Which of the ambassadors is the first one doesn't matter; the translator list can be forward or reverse.
* Ambassadors only speak one language for the sake of this challenge
* Translators speak at least two languages
* The 2-letter language codes do not need to correspond with real languages
* You may assume there is a valid sequence of translators
* If outputting the sequence by value, include the full set of available languages, not just the relevant ones.

Happy Golfing!

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

```
ŒPŒ!€Ẏj@€fƝẠ$ƇḢḊṖ

```

Try it online!

A dyadic link taking the list of translators as the left argument and list of ambassadors (each double-wrapped in a list) as the right argument. Returns a list of translators, each of which is a list of the languages they speak.

Thanks to @KevinCruijssen for saving 2 bytes!

### Explanation

```
ŒPŒ!€Ẏj@€fƝẠ$ƇḢḊṖ | A dyadic link taking a list of translators as left argument and a list of ambassadors (double-wrapped in lists) as right argument

ŒP                | Power set of translators
  Œ!€             | Permutations of each
     Ẏ            | Tighten, i.e. create a single list of all permutations of any length
      j@€         | Join the ambassadors with each set of translators
            $Ƈ    | Filter those where:
           Ạ      |   all
         fƝ       |   the neighbouring pairs have at least one in common
              Ḣ   | Take the first
               Ḋ  | Drop the first ambassador from the start
                Ṗ | Drop the second ambassador from the end

```

# Answer
> 3 votes
# Python 2, ~~138~~ ~~126~~ ~~120~~ ~~117~~ 113 bytes

```
F=lambda a,b,T,*U:a!=b and min([[t]+F(l,b,T,t,*U)for t in T if(t in U)<(a in t)for l in t-{a}]+[2*T],key=len)or[]

```

Try it online!

3 bytes thx to ArBo

Returns a minimal length list of the translators as `set`s of languages, i.e. 'by value', from `T` that allow `a` to talk to `b`.

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

```
æ€œ€`ʒ²š³ªüå€àP}н

```

Inspired by *@NickKennedy*'s Jelly answer, so make sure to upvote him!

Outputs the lists themselves instead of their indices.

Try it online or verify all test cases.

**Explanation:**

```
æ                # Get the powerset of the (implicit) input-list of translators
                 #  i.e. [["ef","gh","bc"],["bc","ab"],["ef","cd","de"]]
                 #   → [[],[["ef","gh","bc"]],[["bc","ab"]],[["ef","gh","bc"],["bc","ab"]],[["ef","cd","de"]],[["ef","gh","bc"],["ef","cd","de"]],[["bc","ab"],["ef","cd","de"]],[["ef","gh","bc"],["bc","ab"],["ef","cd","de"]]]
 €œ              # Get the permutations of each
                 #  → [[[]],[[["ef","gh","bc"]]],[[["bc","ab"]]],[[["ef","gh","bc"],["bc","ab"]],[["bc","ab"],["ef","gh","bc"]]],[[["ef","cd","de"]]],[[["ef","gh","bc"],["ef","cd","de"]],[["ef","cd","de"],["ef","gh","bc"]]],[[["bc","ab"],["ef","cd","de"]],[["ef","cd","de"],["bc","ab"]]],[[["ef","gh","bc"],["bc","ab"],["ef","cd","de"]],[["ef","gh","bc"],["ef","cd","de"],["bc","ab"]],[["bc","ab"],["ef","gh","bc"],["ef","cd","de"]],[["bc","ab"],["ef","cd","de"],["ef","gh","bc"]],[["ef","cd","de"],["ef","gh","bc"],["bc","ab"]],[["ef","cd","de"],["bc","ab"],["ef","gh","bc"]]]]
   €`            # Flatten each one level down (4D list becomes 3D list)
                 #  → [[],[["ef","gh","bc"]],[["bc","ab"]],[["bc","ab"],["ef","gh","bc"]],[["ef","gh","bc"],["bc","ab"]],[["ef","cd","de"]],[["ef","cd","de"],["ef","gh","bc"]],[["ef","gh","bc"],["ef","cd","de"]],[["ef","cd","de"],["bc","ab"]],[["bc","ab"],["ef","cd","de"]],[["ef","cd","de"],["bc","ab"],["ef","gh","bc"]],[["ef","cd","de"],["ef","gh","bc"],["bc","ab"]],[["bc","ab"],["ef","cd","de"],["ef","gh","bc"]],[["bc","ab"],["ef","gh","bc"],["ef","cd","de"]],[["ef","gh","bc"],["ef","cd","de"],["bc","ab"]],[["ef","gh","bc"],["bc","ab"],["ef","cd","de"]]]
     ʒ           # Filter this 3D list by:
      ²š         #  Prepend the second input ambassador
                 #   i.e. [["bc","ab"],["ef","gh","bc"]] and "ab"
                 #    → ["ab",["bc","ab"],["ef","gh","bc"]]
        ³ª       #  Append the third input ambassador
                 #   i.e. ["ab",["bc","ab"],["ef","gh","bc"]] and "ef"
                 #    → ["ab",["bc","ab"],["ef","gh","bc"],"ef"]
          ü      #  For each adjacent pair of translator-lists:
           å     #   Check for each item in the second list, if it's in the first list
                 #    i.e. ["bc","ab"] and ["ef","gh","bc"] → [0,0,1]
            €à   #   Then check if any are truthy by leaving the maximum
                 #    → 1
              P  #  And then take the product to check if it's truthy for all pairs
                 #   i.e. ["ab",["bc","ab"],["ef","gh","bc"],"ef"] → [1,1,1] → 1
     }н          # After the filter: only leave the first list of translator-lists
                 #  i.e. [[["bc","ab"],["ef","gh","bc"]],[["bc","ab"],["ef","gh","bc"],["ef","cd","de"]]]
                 #   → [["bc","ab"],["ef","gh","bc"]]
                 # (which is output implicitly as result)

```

# Answer
> 1 votes
# JavaScript (ES6),  ~~123~~  121 bytes

Expects integers instead of 2-letter codes.

```
(a,b,l)=>((B=g=(m,s,i)=>m>>b&1?B<i||(o=s,B=i):l.map(a=>a.map(M=c=>M|=1<<c)|M&m&&m^(M|=m)&&g(M,[...s,a],-~i)))(1<<a,[]),o)

```

Try it online!

---
Tags: code-golf, graph-theory
---


title: Deal the cards to the players

text:
# Question
Title: Deal the cards to the players
Tonight is card game night! You are the dealer and your task is to write a program to deal the cards to the players.

Given an array of cards and the number of players, you need to split the array of cards into a hand for each player.

## Rules

Your program will receive an non-empty array `A` , as well as a non-zero positive integer `n`. The array should then be split into `n` hands. If the length of the string isn't divisible by `n` any leftover cards at the end should be distributed as evenly as possible.

* If `n==1`, you will need to return an array of array with `A` as it's only element
* If `n` is greater than the length of `A`, you will need to return every hand and an empty hand. if `n = 4` and `array A = [1,2,3]`, you should return `[[1],[2],[3]]` or `[[1],[2],[3],[]]`. You are free to handle the empty hand with empty, undefined or null.
* The array can contain any type rather than a number.
* You should not change the order of the array while dealing. For example `if n = 2` and `A= [1,2,3]`, any result rather than `[[1,3],[2]]` will be invalid.

## Test Cases

```
n   A               Output

1   [1,2,3,4,5,6]   [[1,2,3,4,5,6]]
2   [1,2,3,4,5,6]   [[1,3,5],[2,4,6]]
3   [1,2,3,4,5,6]   [[1,4],[2,5],[3,6]]
4   [1,2,3,4,5,6]   [[1,5],[2,6],[3],[4]]
7   [1,2,3,4,5,6]   [[1],[2],[3],[4],[5],[6]] // or [[1],[2],[3],[4],[5],[6],[]]

```

## Demo Program

```
def deal(cards, n):
	i = 0
	players = [[] for _ in range(n)]
	for card in cards:
		players[i % n].append(card)
		i += 1
	return players

hands = deal([1,2,3,4,5,6], 2)

print(hands)

```

Try it online!

This is , so you the shortest bytes of each language will be the winner.

Inspired from Create chunks from array by chau giang

# Answer
# 05AB1E, ~~3~~ 1 byte

Saved 2 bytes thanks to *Adnan*

```
ι

```

Try it online! or as a Test Suite

**Explanation**

```
ι  # uninterleave

```

Does exactly what the challenge asks for
> 14 votes

# Answer
# , ~~46~~ 25 bytes

```
function(A,n)split(A,1:n)

```

Try it online!

`split`s `A` into groups defined by `1:n`, recycling `1:n` until it matches length with `A`.
> 9 votes

# Answer
# Perl 6, ~~33~~ 24 bytes

```
->\b{*.classify:{$++%b}}

```

Try it online!

Anonymous curried code block that takes a number and returns a Whatever lambda that takes a list and returns a list of lists. This takes the second option when given a number larger than the length of lists, e.g. `f(4)([1,2,3])` returns `[[1],[2],[3]]`

### Explanation:

```
->\b{                  }  # Anonymous code block that takes a number
     *                    # And returns a Whatever lambda
      .classify           # That groups by
               :{$++%b}   # The index modulo the number

```
> 7 votes

# Answer
# Wolfram Language (Mathematica), 28 bytes

```
(s=#;GatherBy[#2,#~Mod~s&])&

```

Try it online!
> 7 votes

# Answer
# Japt, 2 bytes

Takes the array as the first input.

```
óV

```

Try it
> 6 votes

# Answer
# Jelly, ~~6~~ 2 bytes

```
sZ

```

Try it online!

Thanks to @JonathanAllan for saving 4 bytes
> 6 votes

# Answer
# Python 2, 37 bytes

### Code:

```
lambda x,n:[x[i::n]for i in range(n)]

```

Try it online!
> 5 votes

# Answer
# Haskell, 39 bytes

```
import Data.Lists
(transpose.).chunksOf

```

Note: `Data.Lists` is from the third-party library lists, which is not on Stackage and hence will not appear on Hoogle.
> 4 votes

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

```
(|#\)</.]

```

Try it online!

## how (previous explanation, fundamentally the same)

```
] </.~ (| #\)
  </.~          NB. box results of grouping
]               NB. the right arg by...
         |      NB. the remainders of dividing...
       [        NB. the left arg into...
           #\   NB. the length of each prefix of...
              ] NB. the right arg,
                NB. aka, the integers 1 thru
                NB. the length of the right arg

```
> 4 votes

# Answer
# Charcoal, 9 bytes

```
ＩＥθ✂ηιＬηθ

```

Try it online! Link is to verbose version of code. Takes input in the order `[n, A]` and outputs each value on its own line and each hand double-spaced from the previous. Explanation:

```
  θ         First input `n`
 Ｅ          Map over implicit range
    η       Second input `A`
   ✂        Sliced
     ι      Starting at current index
      Ｌη    Ending at length of `A`
        θ   Taking every `n`th element
Ｉ           Cast to string
            Implicitly print

```
> 3 votes

# Answer
# Kotlin, ~~53~~ ~~51~~ 49 bytes

```
{a,n->(0..n-1).map{a.slice(it..a.size-1 step n)}}

```

The old, incorrect solution only worked for divisors of the array length. I'm certain this can be golfed down.

Try it online!
> 3 votes

# Answer
# Wolfram Language (Mathematica), 25 bytes

```
#2[[i;;;;#]]~Table~{i,#}&

```

Try it online!
> 3 votes

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

```
A=>n=>A.map((x,i)=>e[i%=n]=[...e[i]||[],x],e=[])&&e

```

Try it online!

# JavaScript (Node.js), 53 bytes

```
A=>n=>g=(i=n)=>i?[...g(--i),A.filter(_=>i--%n==0)]:[]

```

Try it online!
> 2 votes

# Answer
# TSQL, 44 bytes

```
-- @       : table containing the input
-- column c: value of the card,
-- column a: position on the card in the deck
-- @n      : number of players

DECLARE @ table(a int identity(0,1), c varchar(9))
DECLARE @n int = 4

INSERT @ values('1a'),('2c'),('3e'),('4g'),('5i'),('6k')

SELECT string_agg(c,',')FROM @ GROUP BY a%@n

```

**Try it out**
> 2 votes

# Answer
# Ruby, 81 bytes

```
def s a,n;a.each_with_index.inject(([[]]*n).map(&:dup)){|b,(c,d)|b[d%n]<<c;b};end

```

Try It Online
> 2 votes

# Answer
# APL+WIN 26 or 31 bytes

If individual hands can be represented as columns of a 2D matrix then 26 bytes if an array of arrays then add 5 bytes.

```
(l,n)⍴((l←⌈(⍴a)÷n)×n←⎕)↑a←⎕

```

Try it online! ourtesy of Dyalog Classic

or

```
⊂[1](l,n)⍴((l←⌈(⍴a)÷n)×n←⎕)↑a←⎕

```

Try it online! Courtesy of Dyalog Classic

Explanation:

a←⎕ prompt for array of cards

((l←⌈(⍴a)÷n)×n←⎕)↑ prompt for integer, pad a with zeros to given even hands

(l,n)⍴ create 2D matrix with each column representing each hand

⊂\[1\] if required convert to nested vector - APL array of arrays
> 1 votes

# Answer
# MathGolf, 9 bytes

```
\ô_í\%q╞;

```

Try it online!

## Explanation

```
\           swap top elements (pops both input onto stack)
 ô          start block of length 6
  _         duplicate TOS (will duplicate the list)
   í        get total number of iterations of for loop (the other input)
    \       swap top elements
     %      modulo (picks every n:th item of the list
      q     print without newline
       ╞    discard from left of string/array (makes the next player pick cards starting with the next in the deck)
        ;   discard TOS (removes some junk in the end)

```
> 1 votes

# Answer
# PHP, ~~85~~ ~~83~~ 82 bytes

```
function($a,$n){while($x<$n)$c[]=array_column(array_chunk($a,$n),+$x++);return$c;}

```

Try it online!

This will not be the shortest entry, but I thought it'd be fun to try and do it using PHP array function built-ins. Result: long.

***Output***

```
1   [1,2,3,4,5,6]   [[1,2,3,4,5,6]]
2   [1,2,3,4,5,6]   [[1,3,5],[2,4,6]]
3   [1,2,3,4,5,6]   [[1,4],[2,5],[3,6]]
4   [1,2,3,4,5,6]   [[1,5],[2,6],[3],[4]]
7   [1,2,3,4,5,6]   [[1],[2],[3],[4],[5],[6],[]]
5   ["9C","QD","2S","4H","6D","AS","9D","TH","5C"]  [["9C","AS"],["QD","9D"],["2S","TH"],["4H","5C"],["6D"]]

```
> 1 votes

# Answer
# Java (JDK), 90 bytes

```
A->n->{var o="";for(int h=0,i;h<n;o+="\n")for(i=h++;i<A.length;i+=n)o+=" "+A[i];return o;}

```

Try it online!

Thanks Olivier Grégoire for the lambda and better incrementing while iterating.
> 1 votes

# Answer
# Perl 5 `-la`, ~~66~~ 56 bytes

```
$,=<>;map{push@$_,shift@F}1..$,while@F;say"@$_"for 1..$,

```

Try it online!
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler), 43 bytes

```
a=>b=>{int i=0;return a.GroupBy(_=>i++%b);}

```

Try it online!
> 0 votes

# Answer
# C (gcc), 5 bytes

The compiler flag `-Df=` (req. leading space) fulfills specification. `f(n_cards,n_hands,card_ptr)` evaluates to a pointer to a list of hands.

# Explanation

In C, it is common practice to implement lists of lists as a single interleaved array, when the number of lists remains constant but all lists can be extended. For example, in this case of dealing cards, it is more common for more cards to get added to each hand than more hands to be added, so it would be reasonable to implement a list of hands as an interleaved list. Coincidentally, the "deck" is such a list, and thus we return the parameter unmodified.

This challenge probably should've been sandboxed.
> 0 votes

---
Tags: code-golf, array
---


title: Professor at MIT can read minds!

text:
# Question
Title: Professor at MIT can read minds!
The task is taken from an MIT lecture by Prof. Devadas called You can read minds. A detailed explanation of the trick can be found in the linked video, or in this document. I'll try to explain it in simpler terms.

It turns out this was invented in the 1930's, and is known as the **"Five-Card Trick of Fitch Cheney"**.

---

The trick goes like this:

* Five random cards are chosen from a deck of cards. The audience and your assistant get to see them, but you don't.
* Your assistant (with whom you have practiced) will select four of those cards and show them to you in a specific order. Note that the hidden card is not randomly picked from the 5 cards. The assistant picks a/the card that will make the trick work.
* You will deduce, based on the information you can gather from the four cards what the fifth card is.

---

## How?

Keep the following two points in mind:

1. When choosing 5 random cards, you are guaranteed that *at least* two cards have the same suit1.
2. The image below shows a circle with all the ranks2. Since it's a circle, it's possible to count: **J, Q, K, A, 2, 3** (i.e. modular counting). You are guaranteed that the hidden card does not have the same rank as the first, since they will be of the same suit (explained below). It's always possible to choose the first card and the hidden cards such that the hidden card is between 1 and 6 ranks higher than the first (when counting in circles). If the first card is **1**, then the hidden card will be **2,3,4,5,6 or 7**. If the first card is **J**, then the hidden card will be **Q,K,A,2,3 or 4** and so on.

---

## The algorithm:

**The first card:** This card will have the same suit as the hidden card. The card will also be the reference point you'll use when figuring out the rank of the hidden card.

**The 2nd, 3rd and 4th cards** decodes a value in the inclusive range **1 ... 6**. We'll call the three cards **S, M, L** (smallest card, middle card, largest card). The values will be encoded like this (lexicographic order):

```
S M L   -> 1
S L M   -> 2
M S L   -> 3
M L S   -> 4
L S M   -> 5
L M S   -> 6

```

So, if the rank of the first card is **5**, and the remaining three cards have ranks **4 Q 7** (they are ordered **S L M**), then the last card has rank **5+2=7**. You may choose if the ace should be the highest or lowest card, as long as it's consistent.

If several cards share rank, then the suit will determine the order, where **C \< D \< H \< S**.

---

### Input format:

The four cards will be given as **H3** (three of hearts), **DK** (King of diamonds) and so on. You may choose to take the input the other way around as **3H** and **KD** instead.

The input can be on any convenient format, but you can't combine the list of suits in one variable and the list of ranks in another. `'D5', 'H3' ..` and `[['D',5],['H',3] ...` are both OK, but `'DHCH',[5,3,1,5]` is not. You can't use numbers instead of letters, except for **T**.

### Output

The hidden card, in the same format as the input.

---

### Example

Let's do a walkthrough:

```
Input:
D3 S6 H3 H9

```

We know the hidden card is a diamond, since the first card is a diamond. We also know that the rank is **4,5,6,7,8 or 9** since the rank of the first card is **3**.

The remaining cards are ordered **6,3,9 ==\> M,S,L**, which encodes the value **3**. The hidden card is therefore **3+3=6** of diamonds, thus the output should be **D6**.

### Test cases:

```
C3 H6 C6 S2
C9            # The order is LMS (H6 > C6, and 2 < 6). 3+6=9

SQ S4 S3 ST   # (ST = S10. Format is optional)
S2            # The order is MSL. 12+3=2

HA CA DA SA
H2            # The order is SML. 14+1=2

```

---

This is , so the shortest solution in each language wins. Explanations are encouraged!

---

1There are four suits (**C**lubs, **D**iamonds, **H**earts and **S**pades).

2There are 13 ranks, **2,3,4,5,6,7,8,9,10,J,Q,K,A**. You may choose to use **T** instead of **10**.

# Answer
# JavaScript (ES6), ~~130~~ 102 bytes

Takes input as an array of strings in `"Rs"` format, where **R** is the rank and **s** is the suit. Expects **"T"** for 10's. Aces are low.

```
a=>(s='A23456789TJQK')[([[R,[,S]],B,C,D]=a.map(c=>[s.search(c[0])+14,c]),R+=D<C|2*((D<B)+(C<B)))%13]+S

```

Try it online!

### How?

We first convert each card into an array **\[rank, card\]** where **rank** is a numeric value in **\[14...26\]** and **card** is the original string.

```
[[R, [, S]], B, C, D] = a.map(c => ['A23456789TJQK'.search(c[0]) + 14, c])

```

The rank and suit of the first card are stored in **R** and **S** respectively. The three other cards are stored in **B**, **C** and **D**.

For instance, `['3c','6h','6c','2s']` becomes:

```
[ [ 16, '3c' ], [ 19, '6h' ], [ 19, '6c' ], [ 15, '2s' ] ]
    ^^    ^     <---------->  <---------->  <---------->
    R     S          B             C             D

```

We then compare each pair in **\[ B, C, D \]**. These elements are implicitly coerced to strings when they are compared with each other:

```
[ 19, '6h' ] --> '19,6h'

```

Because both **rank** and **card** are guaranteed to consist of exactly two characters, it is safe to compare in lexicographical order.

We compute:

```
(D < C) | 2 * ((D < B) + (C < B))

```

Below are all the possible combinations:

```
 B, C, D | v0 = D < B  | v1 = C < B  | v2 = D < C  | v2|2*(v0+v1)
---------+-------------+-------------+-------------+--------------
 S, M, L |    false    |    false    |    false    |      0
 S, L, M |    false    |    false    |    true     |      1
 M, S, L |    false    |    true     |    false    |      2
 M, L, S |    true     |    false    |    true     |      3
 L, S, M |    true     |    true     |    false    |      4
 L, M, S |    true     |    true     |    true     |      5

```

Finally, we build the output card using **R**, **S** and the above result:

```
'A23456789TJQK'[(R += D < C | 2 * ((D < B) + (C < B))) % 13] + S

```
> 17 votes

# Answer
# Python 2, ~~143~~ ~~140~~ ~~138~~ ~~136~~ ~~127~~ ~~125~~ ~~124~~ ~~123~~ 121 bytes

```
lambda(S,V),*l:S+N[F(V)+int(`map(sorted(l,key=lambda(s,v):(F(v),s)).index,l)`[1::3],3)*3/10]
N='23456789TJQKA'*2;F=N.find

```

Try it online!

Aces are high

---

Encodes the three cards by finding their position in a sorted list of the cards (`0=smallest, 1=middle, 2=largest`):

```
cards:   [SK, C4, H4]
sorted:  [C4, H4, SK]

ranks:   [ 2            index of SK in sorted
ranks:   [ 2,  0        index of C4 in sorted
ranks:   [ 2,  0,  1    index of H4 in sorted
ranks:   [ 2,  0,  1] = L,S,M

```

This is converted to an integer in base 3 and multiplied by 3, and divided by 10:

```
int('201',3) = 19 -> 19*3//10 = 5

```

The different encodings are:

```
cards            base3    *3   /10
[0, 1, 2]  012     5      15     1
[0, 2, 1]  021     7      21     2
[1, 0, 2]  102     11     33     3
[1, 2, 0]  120     15     45     4
[2, 0, 1]  201     19     57     5
[2, 1, 0]  210     21     63     6

```

---

Saved:

* -2 bytes, thanks to ovs
> 15 votes

# Answer
# Jelly, 33 bytes

```
ØDḊḊ;“TJQKA”p“CDHS”
¢iⱮµḊŒ¿×4+Ḣị¢

```

Try it online!

**Explanation**

The first line is niladic. It yields a list of the 52 cards

```
ØDḊḊ;“TJQKA”p“CDHS”
ØD                   Digits: '0123456789'
  ḊḊ                 Dequeue twice: '23456789'
    ;                Append with...
     “TJQKA”         ...the string 'TJQKA': '23456789TJQKA'. These are the ranks
            p        Cartesian product with...
             “CDHS”  ...the suits.
                     This yields the list of all cards in lexicographic order:
                                 ['2C', '2D', '2H', '2S',
                                  '3C', ...         'AS']

```

In the main link, `¢` calls the result of the first link which is the list of cards.

```
¢iⱮµḊŒ¿×4+Ḣị¢
¢              List of cards
 iⱮ            Index of each (Ɱ) of the inputs in the list.
   µ           New monadic link. The list of indices become this links argument.
    Ḋ          Remove the first one.
     Œ¿        Index of the permutation of the last three items. Gives a number 1-6
               as described in the problem statement.
       ×4      Multiply this by 4 so that when we add to the index of the first
               card we end up in the same suit.
         +Ḣ    Add the first index.
           ị   Use this number to index into...
            ¢  ...the list of cards.

```
> 10 votes

# Answer
# APL (Dyalog Unicode), 49 bytesSBCS

```
⊃x⌽⍨⊃i-4×2-⌊1.8⊥⍋1↓i←⎕⍳⍨x←,⍉'CDHS'∘.,2↓⎕D,'TJQKA'

```

Try it online!

Overview: `'CDHS'∘.,2↓⎕D,'TJQKA'` generates the outer product, so a 2d matrix with `(C2 C3 C4 ...), (D2 D3 D4 ...), ...`. We then transpose this matrix to get `(C2 D2 H2 ...), ...` and then flatten that.

Thanks to @ngn for the `2-⌊1.8⊥`, which takes the order of cards (SML=1 2 3) and grades them (like the 1 to 6 in the OP).

Code explanation:

```
⊃x⌽⍨⊃i-4×2-⌊1.8⊥⍋1↓i←⎕⍳⍨x←,⍉'CDHS'∘.,2↓⎕D,'TJQKA'
                                       ⎕D,'TJQKA' ⍝ Concatenate a list of numbers with TJQKA
                                     2↓           ⍝ Drop 2 (removes "01")
                                  ∘.,             ⍝ Generate the outer product of this prefixed with
                            'CDHS'                ⍝ The suits
                           ⍉                      ⍝ Invert rows/columns
                          ,                       ⍝ Flatten (matrix -> array)
                        x←                        ⍝ Store in x
                      ⍳⍨                          ⍝ Inverted ⍳⍨: find the indices, in our cards,
                     ⎕                            ⍝ of the argument cards
                   i←                             ⍝ Store these indices in i
                 1↓                               ⍝ Remove the first index
                ⍋                                 ⍝ Grade: get ordered indices
         2-⌊1.8⊥                                  ⍝ The magic happens here: get the number from 1 to 6
       4×                                         ⍝ Multiply by 4 to get the same "back" on the card
    ⊃i-                                           ⍝ Substract the result from our first index (which we had discarded)
⊃x⌽⍨                                              ⍝ (Modulated) Index into x (our cards) with this value

```
> 5 votes

# Answer
# Retina, ~~218~~ 208 bytes

```
[JQK]
1$&
T`AJQK`1123
*' G0`
\d+
5**
' G, 1,`
T`CD\HS`d
\d
*
/^(_+)¶\1/(/¶(_+)¶\1/(K`1
/^(_+)¶_+¶\1/(K`2
))K`4
/^(_+)¶_+¶\1/(K`3
/¶(_+)¶\1/(K`5
)))K`6
\d
$+3-$&
(\d+)-(\d+)
$1*_$2*
_{13}(_+)|(_{1,13})
$.($1$2

```

Try it online!

**Explanation:**

```
[JQK]
1$&
T`AJQK`1123

```

Replaces Aces, Jacks, Queens and Kings with 1, 11, 12 and 13. The first two lines prepend a `1` before the letter, and the last transliterates the second digit.

```
*' G0`

```

The `*` indicates that this stage should not modify the working string. This may make the stage seem pointless, but it will be useful later. The `'` splits the working string at every space, and `G0` takes the first one (so it finds the first card).

```
\d+
5**
' G, 1,`'

```

The first two lines multiply the numbers on the cards by 5, then turn them into unary (for example, 5 is represented as \_____), so that we can add smaller amounts for suits later. The final line splits on spaces and keeps the last three cards.

```
T`CD\HS`d
\d
*

```

This converts Clubs, Diamonds, Hearts and Spades to 0, 1, 2 and 3 respectively, and turns the number into unary. Since it is now on the attached of the number part of the card, it will give a unique value for the card, determining how high it is.

```
/^(_+)¶\1/(/¶(_+)¶\1/(K`1
/^(_+)¶_+¶\1/(K`2
))K`4
/^(_+)¶_+¶\1/(K`3
/¶(_+)¶\1/(K`5
)))K`6

```

This finds the ordering of the cards, and the value to add to the first card. For example, on the first line `/^(_+)¶\1_+/(` matches orders that have the middle value larger than the first value. It creates an if-else loop for what to do (as this order matches permutations 1, 2 and 4). `K` marks a constant.

```
\d
$+3-$&

```

Remember earlier when we used `*` to indicate that a stage wouldn't affect the working string? This is where we use it. This stage is a replace stage; it replaces the number to add by `$+3-$&`. `$+3` accesses the `*` stage, and gets the suit and number of the first card, `-` acts as a seperator, and `$&` is the match. So the working string is now `{suit}{original number}-{number to add}`

```
(\d+)-(\d+)
$1*_$2*

```

This turns the two numbers into unary and adds them together.

```
_{13}(_+)|(_{1,13})
$.($1$2

```

The top line captures either the number or the number - 13 (so that we don't get outputs of e.g S16). The bottom line turns the captured number back into base 10, and the result is printed implicitly.
> 4 votes

# Answer
# Charcoal, ~~64~~ 62 bytes

```
≔⪪⭆⁺⭆⁸⁺²ιTJQKA⭆CDHS⁺λι²δ≔Ｅ⟦ηζε⟧⌕διυ§δ⁺⌕δθ×⁴⊕⁺∧⌕υ⌊υ⊗⊕¬⌕υ⌈υ‹⊟υ⊟υ

```

Try it online! Link is to verbose version of code. Uses `T` for 10 and sorts `A` high. The permutation index was not very easily decoded; a different permutation order would have saved me at least three bytes. Explanation:

```
⁺⭆⁸⁺²ιTJQKA

```

Add 2 to all the integers 0 to 7, then concatente them and suffix `TJQKA` for the picture cards and ace. This saves 2 bytes over a string literal, although it turns out that having `A` high would have saved a byte through string compression anyway.

```
≔⪪⭆...⭆CDHS⁺λι²δ

```

Map over the cards and the suits, concatenting the two together. Since this would normally produce a nested array, the results are instead concatenated into a single string which is then split up into pairs of characters again.

```
≔Ｅ⟦ηζε⟧⌕διυ

```

Find the positions of the second, third and fourth cards.

```
⊕⁺∧⌕υ⌊υ⊗⊕¬⌕υ⌈υ‹⊟υ⊟υ

```

Compute the 1-indexed permutation index. The first two permutations have the smallest card first; this is tested via `⌕υ⌊υ`. The other two pairs of permutations are differentiated as to whether the largest card is first; this is tested via `⌕υ⌈υ`. Logical and arithmetic operations then map these tests to the values `0`, `2` and `4`; this is then increased by `1` depending on the comparison between the third and fourth cards, tested via `‹⊟υ⊟υ`. Finally the index is incremented to give the desired encoding.

```
§δ⁺⌕δθ×⁴...

```

Multiply that by 4 repesenting the distance between cards of the same suit, add on the position of the first card, and cyclically index and print the result.
> 3 votes

# Answer
# Python 2, 147 bytes

```
lambda a:a[0][0]+R[h(map(a[1:].index,sorted(a[1:],key=lambda c:(I(c[1]),c))))+I(a[0][1])]
R='A23456789TJQK'*2;I=R.index
h=lambda(x,y,z):x*2+(y>z)+1

```

Try it online!
> 2 votes

# Answer
# Pyth, 42 bytes

```
+hhQ@J+`M}2Tmk"JQKA"+hhKm,xJtdhdQhx.pStKtK

```

Really ugly...

Try it online: Demontration or Test Suite
> 2 votes

# Answer
# T-SQL, 200 bytes

Input is a table variable. Using T for 10, aces are low

Format for cards rank/suit KH,6D,TS

```
DECLARE @ TABLE(c char(2),i int identity(4,-1))
INSERT @
VALUES('2C'),('5H'),('4S'),('3C')

SELECT
substring(max(h+h),max(charindex(q,h)*w)+sum(power(3,i)*r)/10-4,1)+max(right(c,w))FROM(SELECT
rank()over(order
by w,charindex(q,h),c)%4r,*FROM(SELECT'A23456789TJQK'h,i/4w,left(c,1)q,*FROM @)d)y

```

**Try it online** ungolfed

Notice how the SML(1-6) value is calculated:

Logically S,M,L(1,2,3) is converted to a numeric value

> first card is valued 27\*sequence value
>
> second card is valued 9\*sequence value
>
> third card is valued 3\*sequence value
> 2 votes

# Answer
# , 68 bytes

```
r=.'23456789TJQKA'
{:@{.,~0{r|.~1+(r i.0{{.)+(>,{r;'CDHS')A.@/:@i.}.

```

Try it online!

Note: -3 off TIO bytes because the `f=.` doesn't count. Will attempt to golf further and add explanation tomorrow.
> 2 votes

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

```
s=>(k='23456789TJQKA')[p=t=>k.search(s[t][0])+32+s[t][1],u=p(0),(u[0]+u[1]-2*(p(1)<p(2))-2*(p(1)<p(3))-(p(2)<p(3)))%13]+u[2]

```

Try it online!

# JavaScript (Node.js), 125 bytes

```
s=>(k='23456789TJQKA')[p=s.map(t=>k.search(t[0])+32+t[1]),u=p[0],(u[0]+u[1]-2*(p[1]<p[2])-2*(p[1]<p[3])-(p[2]<p[3]))%13]+u[2]

```

Try it online!
> 1 votes

# Answer
# 05AB1E, 37 bytes

```
2TŸ.•3u§•S«.•ôì•âíJuDIkćsD{œJsJk>4*+è

```

Port of *@dylnan*'s Jelly answer, but unfortunately 05AB1E doesn't have the permutation index builtin..

Try it online or verify all test cases.

**Explanation:**

```
2TŸ                # Push the list [2,3,4,5,6,7,8,9,10]
   .•3u§•S         # Push compressed string "jqka", converted to a list of characters
          «        # Merge the lists together
.•ôì•              # Push compressed string "cdhs"
     â             # Create each possible pair
      í            # Reverse each pair
       Ju          # Join each pair together, and convert to uppercase
D                  # Duplicate the deck
 Ik                # Get the index of the cards of the input-list in the deck
   ć               # Extract head; pop and push remainder and head
    s              # Swap to get the remainder
     D{            # Create a sorted copy
       œ           # Get the permutations of that
        JsJk       # Get the index of the unsorted permutation in this permutations list
            >      # Increase it by 1 (since 05AB1E has 0-based indexing)
             4*    # Multiply it by 4
               +   # Add it to the extracted head
                è  # And index it into the duplicated deck
                   # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*) to understand why `.•3u§•` is `"jqka"` and `.•ôì•` is `"cdhs"`.
> 1 votes

---
Tags: code-golf, card-games, encoding
---


# Question
Title: Longest Common Subsequence of Two Strings containing a particular Substring
A subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.

Given three strings A, B and C (note the order) as input, find the length of the longest string S such that:

* **Condition 1:** S is a subsequence of A
* **Condition 2:** S is a subsequence of B
* **Condition 3:** C is a substring of S

.

```
Testcase #1

```

**Input:**

ABCDEF

CDEFAB

B

**Output:**

2

```
Testcase #2

```

**Input:**

HELLO

WORLD

SUCKS

**Output:**

0

```
Testcase #3

```

**Input:**

ABCXD

BCDEF

CD

**Ouput:**

3

```
Testcase #4

```

**Input:**

X

Y

Z

**Ouput:**

0

**Note:**

* The empty string is regarded as a subsequence as well as a substring of every string.
* Assume all input strings are in uppercase.
* Return 0 as output if any of the first two conditions (Condition 1 and Condition 2) is not going to be satisfied using Condition 3.

**Constraints:**

* Assume the lengths of A, B and C will always be between 1 and 3000 (both inclusive)

**Winner:**

One with the shortest code.

# Answer
> 4 votes
## APL (45)

```
⌈/0,⍴¨m/⍨∨/¨⍞∘⍷¨m←⊃∩/{/∘⍵¨↓⍉(z/2)⊤⍳2*z←⍴⍵}¨⍞⍞

```

Explanation:

* `¨⍞⍞`: read two lines. For each of them:
    + `⍳2*z←⍴⍵`: get the numbers from `1` up to `2^length`.
    + `(z/2)⊤`: encode each number as bits
    + `↓⍉`: separate each string of bits into its own array
    + `/∘⍵¨`: and use each of them as a bitmask on the string, giving the subsequences
* `m←⊃∩/`: take the intersection of the two arrays of subsequences, store in `m`
* `∨/¨⍞∘⍷¨`: read a third line, and see in which subsequences it occurs
* `m/⍨`: select those elements from `m` that contained the third line
* `⍴¨`: get the length of each remaining subsequence
* `0,`: add a zero entry in case the resulting list is empty
* `⌈/`: get the highest number in the list

Test cases:

```
      ⌈/0,⍴¨m/⍨∨/¨⍞∘⍷¨m←⊃∩/{/∘⍵¨↓⍉(z/2)⊤⍳2*z←⍴⍵}¨⍞⍞
ABCDEF
CDEFAB
B
 2
      ⌈/0,⍴¨m/⍨∨/¨⍞∘⍷¨m←⊃∩/{/∘⍵¨↓⍉(z/2)⊤⍳2*z←⍴⍵}¨⍞⍞
HELLO
WORLD
SUCKS
 0
      ⌈/0,⍴¨m/⍨∨/¨⍞∘⍷¨m←⊃∩/{/∘⍵¨↓⍉(z/2)⊤⍳2*z←⍴⍵}¨⍞⍞
ABCXD
BCDEF
CD
 3
      ⌈/0,⍴¨m/⍨∨/¨⍞∘⍷¨m←⊃∩/{/∘⍵¨↓⍉(z/2)⊤⍳2*z←⍴⍵}¨⍞⍞
X
Y
Z
 0

```

# Answer
> 4 votes
# SWI-Prolog, 166

```
s(A,[H|R]):-(A=[H|T],s(T,R);s(A,R)).
s([],[]).
r(A,B,C,O):-(r(A,B,C,0,O),!;O=0).
r(A,B,C,M,O):-s(S,A),s(S,B),append([_,C,_],S),length(S,L),L>M,!,(r(A,B,C,L,O),!;L=O).

```

Usage:

```
?- r("abcxd","bcdef","cd",O).
O = 3.

```

# Answer
> 3 votes
**Python (181)**

Will probably be beat soundly by more operator rich languages, but since I so far have nothing to beat... :)

**EDIT: I originally read substring where it said subsequence, this is the subsequence version;**

```
from itertools import*
def f(a,b,c):
 f=lambda x:set(''.join(z)for y in range(len(x))for z in combinations(x,y))
 return max(len(x)for x in f(a).intersection(f(b))if c in x or not x)

```

What it does is basically to create 2 sets of all possible subsequences of the string `a` and the string `b`, intersecting them to find the common ones.

It then simply finds all resulting strings that contain the string `c` and prints the length of the longest matching string.

# Answer
> 3 votes
# Brachylog, 12 bytes, language postdates challenge

```
k⊇ᵐ=h.s~t?∨0

```

Try it online!

This is a function. The TIO link uses a command-line argument that allows functions to be run like full programs.

## Explanation

```
k⊇ᵐ=h.s~t?∨0
k             Take the input, apart from the last element.
 ⊇ᵐ           Find the longest subsequence of each element
   =          such that those subsequences are equal
    h         and that subsequence
      s       has a substring
       ~t?    that's the last element of the input.
     .        If you can, return the subsequence.
          ∨0  If all else fails, return 0.

```

# Answer
> 2 votes
### GolfScript, 45 characters

```
n/)`{?)}+\{['']\1/{`{1$\+}+%}/}/&\,{,}%0+$-1=

```

Takes input as three lines on STDIN. Take a test run here.

*Short explanation of the code:*

```
n/     # split the input at newline into three strings
)`           # take the last one and stringify it
{?)}+        # and build a code block to filter for any string
             # which has that one as a substring (for later use)
\{           # now loop over the remaining two strings and
             # build their subsequences
  ['']       # start with the set of the empty string
  \1/{       # loop over each character of the string
    `{       # apply code block to each member of the set
      1$\+   # copy member and add the current character
    }+%      # -> set is updated with latest character
  }/
}/
&            # take the common subsequences
\,           # apply the filter block from above
{,}%         # from each string take length
0+           # add zero (if empty set was returned)
$-1=         # sort and take last element (largest)

```

# Answer
> 2 votes
# Haskell, 90 81

Haskell provides everything you need in Data.List:

```
s=subsequences
f a b c=maximum$map length$filter(isInfixOf c)$intersect(s a)(s b)

```

If only the function names were shorter :)

# Answer
> 1 votes
# Mathematica ~~150~~ 125

```
f[{a_,b_,c_}]:=({z=Subsets[Characters@#]&,s};s=Select[""<>#&/@(z@a⋂z@b),!StringFreeQ[#,c]&];
If[s=={},0,StringLength[s[[-1]]]])

```
* `Characters` converts a string into a list of characters.
* `Subsets` finds all the subsequences (held as lists of characters).
* `s` refers to the list of ALL common subsequences (not the same a S).
* `s[[-1]]` is the last (and largest) common subsequence; it is equal to S as defined in the question.

**Test Cases**

```
f[{"ABCDEF", "CDEFAB", "B"}]

```

> 2

---

```
f[{"HELLO", "WORLD", "SUCKS"}]

```

> 0

---

```
f[{"ABCXD", "BCDEF", "CD"}]

```

> 3

---

```
f[{"X", "Y", "Z"}]

```

> 0

# Answer
> 1 votes
## **Perl, 122**

```
chomp(($A,$B,$C)=<>);$A=~s/(.)/($1)?.*?/g;$_=join'',map{$$_}1..$#-and/$C/&&$%<($-=length)and$%=$-while$B=~/.*?$A/g;print$%

```

The program expects 3 strings on STDIN and prints a number to STDOUT. Here it is re-written as sub for easier testing:

```
use feature 'say';
sub L{
    ($A,$B,$C,$%)=(@_,0);
    $A=~s/(.)/($1)?.*?/g;
    $_=join'',map{$$_}1..$#-and/$C/&&$%<($-=length)and$%=$-while$B=~/.*?$A/g;
    $%
}
say L(qw/ABCDEF CDEFAB B/);
say L(qw/HELLO WORLD SUCKS/);
say L(qw/ABCXD BCDEF CD/);
say L(qw/X Y Z/);

```

and

```
perl LCSoTS.pl
2
0
3
0

```

So, **122** even with ugly byte-consuming chomping at the start. I hope no bugs crept in while I golfed it to this size. And not sure about scalability, but let it be the question of hardware :-).

# Answer
> 1 votes
# Brachylog, 13 bytes

```
~c~gᵗ⟨⊇ᵛs⟩l|∧

```

Try it online!

I didn't bother scrolling down far enough to notice that ais had already answered in Brachylog before I wrote this, but it looks like his answer doesn't actually output the length. It's way shorter doing what it does (it could be golfed down to the 10-byte `k⊇ᵛ.s~t?∨` with the verify metapredicate and by leaving the output in case of failure to simply default to 0, and then every other integer), but if you try to get it to output the length it ends up tying this (while still making a lot more sense than anything that handles a set number of arguments with `~c`!): `k⊇ᵛXs~t?∧Xl.∨`

A remarkably confusing explanation of my original solution:

```
~c               A partition of
                 the input
    ᵗ            such that its last element
  ~g             is a list containing one element
  ~gᵗ            which is replaced with that element
     ⟨   ⟩       is a list of two elements
          l      such that the implicit variable the length of which
           |     is the output
     ⟨⊇ᵛ ⟩       is a subsequence of both elements of the first element of the partition
     ⟨  s⟩       and has the last element of the partition as a substring.
           |     If it's not possible to find such a subsequence,
            ∧    leave the output variable unconstrained, so it will default to 0.

```

`~chᵗ⟨⊇ᵛs⟩l|∧` is one byte shorter, but provides an incorrect output when the second element of the input is a substring of a subsequence of the first, like this or this. `~ctᵗ⟨⊇ᵛs⟩l|∧` completely disregards the second element of the input.

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


title: Primes other than Optimus

text:
# Question
Title: Primes other than Optimus
## Challenge

Given an input integer `n > 0`, output the number of primes (*other* than `n`, if `n` itself is prime) that can be produced by altering one digit in the decimal expansion of n (without changing the number of digits).

## Examples

For example, `n = 2`. By altering one digit in the decimal expansion of `2`, we can come up with three additional prime numbers, `3, 5, 7`, so `a(n) = 3`.

For another example, `n = 13`. By altering one digit, you can get primes `11, 17, 19, 23, 43, 53, 73, 83`, so `a(13) = 8`.

For a final example, `n = 20`. By altering one digit, you can get primes `23, 29`, so `a(20) = 2`.

## Sequence

Here are the first 20 terms to get you started. This is OEIS A048853.

`4, 3, 3, 4, 3, 4, 3, 4, 4, 4, 7, 4, 8, 4, 4, 4, 7, 4, 7, 2`

## Rules

* The input and output can be assumed to fit in your language's native integer type.
* The input and output can be given in any convenient format.
* Ignore leading zeros (for example, `03` is not a prime number under this formulation).
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* If possible, please include a link to an online testing environment so other people can try out your code!
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
> 10 votes
# 05AB1E, ~~17~~ ~~16~~ ~~14~~ 11 bytes

```
ā°`<Ÿʒ.L}pO

```

Explanation:

```
ā             Push inclusive range from 1 to the length of the input
 °            Raise 10 to the power of each element
  `           Push each element to the stack
   <          Decrement the topmost element
    Ÿ         Inclusive range
              For 13, this creates an array like [10 11 12 13 14 .. 98 99]
     ʒ.L}     Only keep elements with a levenshtein distance to the input of
              exactly one
         p    Check each element for primality
          O   Sum

```

Try it online! or up to 100.

# Answer
> 5 votes
# Python 2, ~~146 136 127 121~~ 118 bytes

Thanks to @Mr.Xcoder for suggestions

```
lambda I:sum(all(i%v for v in range(2,i))*sum(z!=x for z,x in zip(I,`i`))==1for i in range(1+10**~-len(I),10**len(I)))

```

Explanation:

Generate numbers with length equal to input length, skipping first (1,10,100,1000,... )

```
for i in range(1+10**~-len(I),10**len(I))

```

Check that generated number differs from input by only one digit

```
sum(z!=x for z,x in zip(I,`i`))==1

```

Check for prime

```
all(i%v for v in range(2,i))

```

Count

```
sum(...)

```

Try it online!

# Answer
> 4 votes
# Jelly, ~~21~~ ~~18~~ 15 bytes

3 bytes thanks to Dennis.

```
æḟ⁵æR×⁵$DnDS€ċ1

```

Try it online! or Verify all testcases.

# Answer
> 4 votes
# Javascript (ES6) 148 bytes

Takes the input as a string and returns as a number

```
n=>(n.replace(/./g,"$`a$' ").split` `.map(s=>s&&[..."0123456789"].map(d=>r+=+(t=s.replace(/a/,d))[0]&&t^n&&(p=v=>t>1&(--v<2||t%v&&p(v)))(t)),r=0),r)

```

**Example code snippet:**

```
f=
n=>(n.replace(/./g,"$`a$' ").split` `.map(s=>s&&[..."0123456789"].map(d=>r+=+(t=s.replace(/a/,d))[0]&&t^n&&(p=v=>t>1&(--v<2||t%v&&p(v)))(t)),r=0),r)

for(var k=1;k<=20;k++)
  o.innerText+=f(""+k)+" "
```

```
<pre id=o></pre>
```

# Answer
> 3 votes
# JavaScript (ES6), ~~153~~ ~~142~~ 139 bytes

```
n=>([...n].map((c,i,[...a])=>[...''+1e9].map((u,j)=>s+=j+i&&j!=c?p((a.splice(i,1,j),a.join``)):0),s=0,p=q=>eval('for(k=q;q%--k;);k==1')),s)

```

Accepts input as a string. Undefined behavior for invalid input, though it should terminate without error on any string I can think of. Not necessarily before the heat-death of the universe though, particularly for long strings.

### Demo

```
f=
n=>([...n].map((c,i,[...a])=>[...''+1e9].map((u,j)=>s+=j+i&&j!=c?p((a.splice(i,1,j),a.join``)):0),s=0,p=q=>eval('for(k=q;q%--k;);k==1')),s)
console.log([...''+1e19].map((_,i)=>f(i+1+'')).join())
i.onchange=()=>console.log(f(i.value))
```

```
<input id=i>
```

### Improvements

Saved 11 bytes by refactoring the `reduce()` calls into `map()` calls, and by implicitly copying the array `a` in the function parameter, instead of in within the context of the `splice()` call.

Saved 3 bytes thanks to @Neil's suggestion to convert `[...Array(10)]` to `[...''+1e9]`.

### Unminified code

```
input => (
  [...input].map(
    (char, decimal, [...charArray]) =>
      [...'' + 1e9].map(
        (unused, digit) => sum +=
          digit + decimal && digit != char ?
            prime(
              (
                charArray.splice(decimal, 1, digit)
                , charArray.join``
              )
            ) :
            0
      )
    , sum = 0
    , prime = test => eval('for(factor = test; test % --factor;); factor == 1')
  )
  , sum
)

```

### Explanation

The function uses a two-level `map()` to sum the amount of permutations that pass the primality test, which was borrowed and modified from this answer.

### <sub>(Original answer)</sub>

```
reduce((accumulator, currentValue, currentIndex, array) => aggregate, initialValue)

```

So for example, to calculate the sum of an array, you would pass an `initialValue` of `0`, and return an `aggregate` equal to `accumulator + currentValue`. Modifying this approach slightly, we instead calculate the number of permutations that pass the primality test:

```
reduce(
  (passedSoFar, currentDecimal, currentIndex, digitArray) =>
    isValidPermutation() ?
      passedSoFar + prime(getPermutation()) :
      passedSoFar
  , 0
)

```

That is essentially the inner `reduce()`, which iterates all the permutations of the `digitArray` by changing each `decimal` to a specific `permutatedDigit`. We then need an outer `reduce()` to iterate all possible `permutatedDigit`'s with which to replace each `decimal`, which is just `0-9`.

### Abnormalities in implementation

`[...''+1e9].map((u,j)=>...` was the shortest way @Neil could think of to iterate an argument `0` through `9`. It would be preferable to do so with `u`, but `u` is not useful for each element in the array, in this case.

`i+j` in the ternary condition checks to ensure that `0` is not a possible permutation of the leading digit, as per the challenge specification. `j!=c` ensures that the original `n` is not a candidate to go through the primality test.

`(a.splice(i,1,j),a.join``)` is kind of a mess. `splice()` replaces the digit at `decimal == i` with the `permutatedDigit == j`, but since `splice()` returns the removed elements (in this case, would be equal to `[a[i]]`) instead of the modified array, we must use the comma operator to pass the modified array `a` to the primality test, but not before `join()`ing it into a number string.

Lastly, the `eval()` is to save a byte since, compared to the more canonical approach, it is shorter:

```
q=>eval('for(k=q;q%--k;);k==1')

```

```
q=>{for(k=q;q%--k;);return k==1}

```

The reference to the prime test `p` is initialized in an unused argument to the `map()` call.

# Answer
> 3 votes
# Mathematica, 105 bytes

```
F=Count[Range[f=IntegerDigits;g=10^Length@f@#/10,10g],n_/;PrimeQ@n&&MatchQ[f@n-f@#,{x=0...,_,x}]&&n!=#]&;

```

Try it online!

`Function` which expects a positive integer `#`. Sets `f` equal to the function `IntegerDigits` which returns the list of digits of its input. We take the `Range` from `g` to `10g` (inclusive), where `g=10^Length@f@#/10` is the largest power of `10` less than or equal to the input `#`, then `Count` the `n` such that `PrimeQ@n&&MatchQ[f@n-f@#,{x=0...,_,x}]&&n!=#`. `PrimeQ@n` checks whether `n` is prime, `MatchQ[f@n-f@#,{x=0...,_,x}]` checks whether the difference between the list of digits of `n` and `#` is of the form `{0..., _, 0...}`, and `n!=#` ensures that `n` and `#` are `Unequal`.

# Answer
> 2 votes
# Python 2, 134 bytes

```
lambda x,r=range,l=len:sum(~-f*(~-l(x)==sum(`f`[t]==x[t]for t in r(l(x))))and all(f%v for v in r(2,f))for f in r(10**~-l(x),10**l(x)))

```

Try it online!

More elegant, longer version:

```
lambda x,r=range,l=len:l(filter(lambda f:(~-f*(~-l(x)==sum(`f`[t]==x[t]for t in r(l(x)))))*all(f%v for v in r(2,f)),r(10**~-l(x),10**l(x))))

```

The input is taken as a String.

---

# Explanation (older version)

* `lambda x,r=range,l=len:` \- Defines a lambda with a String parameter `x` and two constant parameters `r=range` and `l=len`.
* `sum(1...)` \- Get the length, which saves 1 byte over `len([...])`.
* `for f in r(10**~-l(x),10**l(x))` \- Generates absolutely all the numbers with the same order of magnitude as the input (expect for `0`). For instance, an input of `3`, would result in `[1, 2, 3, 4, 5, 6, 7, 8, 9]`.
* `sum(1for t in r(l(x))if`f`[t]==x[t])==~-l(x)and f>1` \- Checks if the current number is exactly 1 digit away from the input, and that it is higher than 1.
* `all(f%v for v in r(2,f))` \- Checks if the current number is prime.

# Answer
> 2 votes
# Husk, 32 bytes

```
Lof§&ȯ=1Σzo±≠d⁰o=Ld⁰L↑o≤Ld⁰Lmdİp

```

Try it online!

### Ungolfed/Explanation

```
                              İp  -- get all primes
                            md    -- and convert them to list of digits
                     ↑o≤   L      -- take as long as the lenghth of these digit lists are ≤ ..
                        Ld⁰       -- .. the number of digits of input
 of                               -- from those primes filter:
               o=Ld⁰L             --   same number of digits as input
   §&                             --   and
        Σz                        --   the number of..
          o±≠d⁰                   --   .. digits that differ from input digits ..
     ȯ=1                          --   .. must be one
L                                 -- finally count them

```

# Answer
> 1 votes
# JavaScript (ES6), 137 bytes

```
i=(a=prompt()).length;s=0;while(i--)for(j=0;j<=9;j++){(b=[...a]).splice(i,1,j);k=b=b.join('');while(b%--k);s+=i+j&&a[i]!=j&&k==1}alert(s)
```

Adapts my other answer into a full-program submission using the Web API methods `prompt()` and `alert()`.

# Answer
> 1 votes
# Bean, 126 bytes

```
00000000: a64d a065 8050 80a0 5d20 8001 a64d a06f  ¦M e.P. ] ..¦M o
00000010: 8025 39b5 cb81 2065 27a6 4da0 6680 2581  .%9µË. e'¦M f.%.
00000020: 0035 cb81 2066 27a6 53d0 80cd a05e 8043  .5Ë. f'¦SÐ.Í ^.C
00000030: cf20 5d00 2080 82a0 65a5 3a20 66a6 4da0  Ï ]. .. e¥: f¦M
00000040: 6780 4da0 5e80 53d0 80a0 5e20 807b 2300  g.M ^.SÐ. ^ .{#.
00000050: b5cc a05e 8f4b c120 6728 264d a06f 814e  µÌ ^.KÁ g(&M o.N
00000060: cecc a065 8b20 6681 4cd0 84a0 5d20 6581  ÎÌ e. f.LÐ. ] e.
00000070: 2066 814c a067 8025 3a26 206f b130        f.L g.%:& o±0

```

Try it online!

An adaption of my full-program JavaScript submission.

### JavaScript Equivalent

```
i=a.length
s=0
while(i--){
  j=10
  while(j--){
    (b=[...a]).splice(i,1,j)
    k=b=b.join('')
    while(b%--k);
    s+=i+j&&a[i]!=j&&k==1
  }
}
s

```

### Explanation

`a` is implicitly initialized as the first line of input as a string and the last statement `s` is implicitly output, which contains the sum of prime permutations.

# Answer
> 1 votes
# PHP, ~~151~~ ~~147~~ ~~141~~ ~~140~~ ~~136~~ ~~134~~ ~~129~~ 128 bytes

*-6 bytes thanks to @Einacio; -1 byte thanks to @Titus*

```
<?php for($i=$m=10**strlen($n=$argv[1]);$i-->$m/10;)if(levenshtein($n,$i)==$f=$t=1){while($t<$i)$f+=$i%$t++<1;$c+=$f==2;}echo$c;

```

Try it online!

Formatted, with comments:

```
<?php
// Work through each integer with the same number of digits as the input $argv[1].
for ($i = $m = 10 ** strlen($n = $argv[1]); $i-- > $m / 10;)
    // Is it exactly one digit different from the input?
    if (levenshtein($n, $i) == $f = $t = 1) {
        // Count its factors.
        while ($t < $i) $f += $i % $t++ < 1;
        // If there are exactly 2 factors then it's a prime, so increment the counter.
        $c += $f == 2;
    }
// Print the final count.
echo $c;

```

To keep it as short as I could, I've:

* combined assignments `$f = $t = 1`;
* snook in a `++` increment as part of another expression `$f += $i % $t++ == 0` (the increment is executed *after* the modulus operation and so does not affect its result);
* and rather than using an `if` statement for a conditional increment have utilised the fact that boolean true when cast as an integer becomes 1, using `$c += $f == 2;` rather than `if ($f == 2) $c++;`.

# Answer
> 1 votes
# Japt, ~~28~~ 23 bytes

*-5 bytes thanks to @ETHproductions.*

```
¬x@AÇ|Y©+UhYZsÃâ kUn)èj

```

Takes a string as input.

Try it online!

# Answer
> 1 votes
# Perl 6, 83 bytes

```
{+grep &is-prime,m:ex/^(.*)(.)(.*)$/.map:{|map
.[0]~*~.[2],grep *-.[1],?.[0]..9}}

```

Try it online!

# Answer
> 0 votes
# PHP, 100+1 bytes

```
for(;~($a=$argn)[$i];$i++)for($d=-!!$i;$d++<9;$c+=$k==1)for($a[$i]=$d,$k=$a;--$k&&$a%$k;);echo$c-$i;

```

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

**breakdown**

```
for(;~($n=$argn)[$i];$i++)  # loop through argument digits, restore $n in every iteration
    for($d=-!!$i;               # loop $d from 0 (1 for first digit)
        $d++<9;                 # ... to 9
        $c+=$k==1                   # 3. if divisor is 1, increment counter
    )
        for($n[$i]=$d,              # 1. replace digit
            $k=$n;--$k&&$n%$k;      # 2. find largest divisor of $n smaller than $n
        );
echo$c-$i;                  # print counter - length

```

# Answer
> 0 votes
# Java 8, ~~201~~ 194 bytes

```
n->{String s=n+"";int r=0,i=0,j,k,t,u,l=s.length();for(;i<l;i++)for(j=0;++j<10;r+=n==u|t<2?0:1)for(u=t=new Integer(s.substring(0,i)+j+(i<l?s.substring(i+1):"")),k=2;k<t;t=t%k++<1?0:t);return r;}

```

**Explanation:**

Try it here.

```
n->{                        // Method with integer as parameter and return-type
  String s=n+"";            //  String representation of the input-int
  int r=0,                  //  Result-integer
      i=0,j,k,              //  Index-integers
      t,u,                  //  Temp integers
      l=s.length();         //  Length of the String
  for(;i<l;i++)             //  Loop (1) from 0 to `l` (exclusive)
    for(j=0;++j<10;         //   Inner loop (2) from 1 to 10 (exclusive)
        r+=                 //     And after every iteration, raise the result by:
           n==u             //      If the current number equals the input
           |t<2?            //      or it is not a prime:
            0               //       Add nothing to the result-counter
           :                //      Else:
            1)              //       Raise the result-counter by one
      for(                  //    Inner loop (3)
          u=t=              //     First set both `u` and `t` to:
              new Integer(  //      Convert the following String to an integer:
               s.substring(0,i)
                            //       Get the substring from 0 to `i` (exclusive)
               +j           //       + `j`
               +(i<l?       //       + If `i` is smaller than the String-length:
                  s.substring(i+1)
                            //          The substring from 0 to `i` (inclusive)
                 :          //         Else:
                  "")),     //          Nothing
          k=2;              //     And start `k` at 2
              k<t;          //     Continue looping as long as `k` is smaller than `t`
        t=t%k++<1?          //     If `t` is divisible by `k`:
           0                //      Change `t` to 0
          :                 //     Else:
           t                //      Leave `t` as is
      );                    //    End of inner loop (3)
                            //    (`t` remained the same after loop 3? -> It's a prime)
                            //   End of inner loop (2) (implicit / single-line body)
                            //  And of loop (1) (implicit / single-line body)
  return r;                 //  Return the result-counter
}                           // End of method

```

`new Integer(s.substring(0,i)+j+(i<l?s.substring(i+1):"")` will result in these integers:

For `0-9`: `1, 2, 3, 4, 5, 6, 7, 8, 9`.
For `10`: `10, 20, 30, 40, 50, 60, 70, 80, 90, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19`.
For `11`: `11, 21, 31, 41, 51, 61, 71, 81, 91, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19`.
etc.

# Answer
> 0 votes
# JavaScript (ES7), 118 bytes

Takes input as a string.

```
n=>[...2**29+'4'].map(d=>n.replace(/./g,c=>s+=d+i>0&(P=k=>N%--k?P(k):N-n&&k==1)(N=p+d+n.slice(++i),p+=c),i=p=0),s=0)|s

```

Try it online!

### Commented

```
n =>                        // n = input number (as a string)
  [...2**29 + '4']          // generate "5368709124" (all decimal digits)
  .map(d =>                 // for each digit d in the above string:
    n.replace(/./g, c =>    //   for each digit c in n:
      s +=                  //     increment s if the following code yields 1:
        d + i > 0 & (       //       if this is not the first digit of n or d is not "0":
          P = k =>          //         P = recursive function taking k and using N:
            N % --k ?       //           decrement k; if k is not a divisor of N:
              P(k)          //             do recursive calls until it is
            :               //           else:
              N - n &&      //             return true if N is not equal to n
              k == 1        //             and k is equal to 1 (i.e. N is prime)
          )(                //         initial call to P ...
            N =             //           ... with N defined as:
              p +           //             the current prefix p
              d +           //             followed by d
              n.slice(++i), //             followed by the trailing digits
                            //             (and increment the pointer i)
            p += c          //           append c to p
          ),                //         end of initial call
          i = p = 0         //         start with i = p = 0
    ),                      //   end of replace()
    s = 0                   //   start with s = 0
  ) | s                     // end of map(); return s

```

# Answer
> 0 votes
# Ruby with `-rprime`, 101 bytes

`-rprime` imports the Prime module into Ruby. Get all primes up to \\$10^{floor(log\_{10} n)+1}\\$ and count how many have the same number of digits from \\$n\\$ and are also 1 digit off.

```
->n{d=n.digits;Prime.each(10**l=d.size).count{|x|d.zip(e=x.digits).count{|a,b|a==b}==l-1&&e.size==l}}

```

Try it online!

---
Tags: code-golf, sequence, arithmetic, primes
---


title: Cuban Primes

text:
# Question
Title: Cuban Primes
Given a natural number \\$n\\$, return the \\$n\\$-th cuban prime.

### Cuban Primes

A cuban prime is a prime number of the form

$$p = \frac{x^3-y^3}{x-y}$$

where \\$y\>0\\$ and \\$x = 1+y\\$ or \\$x = 2+y\\$

### Details

* You may use 0 or 1 based indexing, whatever suits you best.
* You can return the \\$n\\$-th prime given the index \\$n\\$ or the first \\$n\\$ primes in increasing order, or alternatively you can return an infinite list/generator that produces the primes in increasing order.

### Test cases

The first few terms are following:

```
(#1-13)   7, 13, 19, 37, 61, 109, 127, 193, 271, 331, 397, 433, 547,
(#14-24) 631, 769, 919, 1201, 1453, 1657, 1801, 1951, 2029, 2269, 2437,
(#25-34) 2791, 3169, 3469, 3571, 3889, 4219, 4447, 4801, 5167, 5419,
(#35-43) 6211, 7057, 7351, 8269, 9241, 10093, 10267, 11719, 12097,
(#44-52) 12289, 13267, 13669, 13873, 16651, 18253, 19441, 19927, 20173

```

More terms can be found on OEIS: They are split up in two sequences, depending on wheter \\$x = 1+y \\$ or \\$x = 2+y\\$: A002407 and A002648

# Answer
# JavaScript (V8), 54 bytes

A full program that prints cuban primes forever.

```
for(x=0;;){for(k=N=~(3/4*++x*x);N%++k;);~k||print(-N)}

```

Try it online!

*NB: Unless you have infinite paper in your printer, **do not attempt to run this in your browser console**, where `print()` may have a different meaning.*

---

# JavaScript (ES6),  ~~63 61 60~~  59 bytes

Returns the \\$n\\$-th cuban prime, 1-indexed.

```
f=(n,x)=>(p=k=>N%++k?p(k):n-=!~k)(N=~(3/4*x*x))?f(n,-~x):-N

```

Try it online!

### How?

This is based on the fact that cuban primes are primes of the form:

$$p\_n=\left\lfloor\frac{3n^2}{4}\right\rfloor+1,\\;n\ge3$$

The above formula can be written as:

$$p\_n=\begin{cases} \dfrac{3n^2+1}{4}\\;\text{ if }n\text{ is odd}\\ \dfrac{3n^2+4}{4}\\;\text{ if }n\text{ is even} \end{cases} $$

or for any \\$y\>0\\$:

$$p\_{2y+1}=\dfrac{3(2y+1)^2+1}{4}=3y^2+3y+1$$ $$p\_{2y+2}=\dfrac{3(2y+2)^2+4}{4}=3y^2+6y+4$$

which is \\$\dfrac{x^3-y^3}{x-y}\\$ for \\$x=y+1\\$ and \\$x=y+2\\$ respectively.
> 24 votes

# Answer
# 05AB1E, ~~16~~ ~~12~~ 9 bytes

Generates an infinite list.
Saved 4 bytes with *Kevin Cruijssen's* port of Arnaulds formula.
Saved another 3 bytes thanks to *Grimy*

```
∞n3*4÷>ʒp

```

Try it online!

**Explanation**

```
∞          # on the list of infinite positive integers
 n3*4÷>    # calculate (3*N^2)//4+1 for each
       ʒp  # and filter to only keep primes

```
> 7 votes

# Answer
# , ~~75~~ 73 bytes

```
n=scan()
while(F<n)F=F+any(!(((T<-T+1)*1:4-1)/3)^.5%%1)*all(T%%(3:T-1))
T

```

Try it online!

-2 bytes by noticing that I can remove brackets if I use `*` instead of `&` (different precedence).

Outputs the `n`th Cuban prime (1-indexed).

It uses the fact (given in OEIS) that Cuban primes are of the form \\$p=1+3n^2\\$ or \\$4p=1+3n^2\\$ for some \\$n\\$, i.e. \\$n=\sqrt{\frac{a\cdot p-1}{3}}\\$ is an integer for \\$a=1\\$ or \\$a=4\\$.

The trick is that no prime can be of the form \\$2p=1+3n^2\\$ or \\$3p=1+3n^2\\$ (\*), so we can save 2 bytes by checking the formula for \\$a\in\\{1, 2, 3, 4\\}\\$ (`1:4`) instead of \\$a\in\\{1, 4\\}\\$ (`c(1,4)`).

Slightly ungolfed version of the code:

```
# F and T are implicitly initialized at 0 and 1
# F is number of Cuban primes found so far
# T is number currently being tested for being a Cuban prime
n = scan()                       # input
while(F<n){
  T = T+1                        # increment T
  F = F +                        # increment F if
    (!all(((T*1:4-1)/3)^.5 %% 1) # there is an integer of the form sqrt(((T*a)-1)/3)
     & all(T%%(3:T-1)))          # and T is prime (not divisible by any number between 2 and T-1)
  }
T                                # output T

```

(\*) No prime can be of the form \\$3p=1+3n^2\\$, else \\$1=3(p-n^2)\\$ would be divisible by \\$3\\$.

No prime other than \\$p=2\\$ (which isn't a Cuban prime) can of the form \\$2p=1+3n^2\\$: \\$n\\$ would need to be odd, i.e. \\$n=2k+1\\$. Expanding gives \\$2p=4+12k(k+1)\\$, hence \\$p=2+6k(k+1)\\$ and \\$p\\$ would be even.
> 7 votes

# Answer
# Wolfram Language (Mathematica), 66 65 56 bytes

```
(f=1+⌊3#/4#⌋&;For[n=i=0,i<#,PrimeQ@f@++n&&i++];f@n)&

```

Try it online!

* J42161217 **-1** by using `⌊ ⌋` instead of `Floor[ ]`
* attinat

+ **-1** by using `⌊3#/4#⌋` instead of `⌊3#^2/4⌋`
    + **-8** for `For[n=i=0,i<#,PrimeQ@f@++n&&i++]` instead of `n=2;i=#;While[i>0,i-=Boole@PrimeQ@f@++n]`
> 5 votes

# Answer
# Java 8, ~~94~~ ~~88~~ ~~86~~ 84 bytes

```
v->{for(int i=3,n,x;;System.out.print(x<1?++n+" ":""))for(x=n=i*i++*3/4;~n%x--<0;);}

```

-6 bytes by using the Java prime-checker of *@SaraJ*, so make sure to upvote her!
-2 bytes thanks to *@OlivierGrégoire*. Since the first number we check is `7`, we can drop the trailing `%n` from Sara's prime-checker, which is to terminate the loop for `n=1`.
-2 bytes thanks to *@OlivierGrégoire* by porting *@Arnauld*'s answer.

Outputs space-delimited indefinitely.

Try it online.

**Explanation (of the old 86 bytes version):** *TODO: Update explanation*

Uses the formula of *@Arnauld*'s JavaScript answer: \\$p\_n=\left\lfloor\frac{3n^2}{4}\right\rfloor+1,\\;n\ge3\\$.

```
v->{                     // Method with empty unused parameter and no return-type
  for(int i=3,           //  Loop-integer, starting at 3
          n,x            //  Temp integers
      ;                  //  Loop indefinitely:
      ;                  //    After every iteration:
       System.out.print( //     Print:
        n==x?            //      If `n` equals `x`, which means `n` is a prime:
         n+" "           //       Print `n` with a space delimiter
        :                //      Else:
         ""))            //       Print nothing
    for(n=i*i++*3/4+1,   //   Set `n` to `(3*i^2)//4+1
                         //   (and increase `i` by 1 afterwards with `i++`)
        x=1;             //   Set `x` to 1
        n%++x            //   Loop as long as `n` modulo `x+1`
                         //   (after we've first increased `x` by 1 with `++x`)
             >0;);}      //   is not 0 yet
                         //   (if `n` is equal to `x`, it means it's a prime)

```
> 3 votes

# Answer
# Wolfram Language (Mathematica), 83 bytes

```
(t=1;While[Length[l=Select[Join@@Array[{(v=3#^2+1)+3#,v}&,t++],PrimeQ]]<#];Sort@l)&

```

Try it online!
> 2 votes

# Answer
# Jelly, 12 bytes

```
²×3:4‘
ÇẒ$#Ç

```

Try it online!

Based on @Arnauld’s method. Takes n on stdin and returns that many Cuban primes.
> 2 votes

# Answer
# Wolfram Language (Mathematica), 83 bytes

This solution will output the n-th Cuban prime with the added benefits of being fast and remembering all previous results in the symbol f.

```
(d:=1+3y(c=1+y)+3b c;e:=If[PrimeQ@d,n++;f@n=d];For[n=y=b=0,n<#,e;b=1-b;e,y++];f@#)&

```

Try it online!
> 1 votes

# Answer
# Python 3, 110 108 102 bytes

Similar method to my Mathematica answer (i.e. `isPrime(1+⌊¾n²⌋) else n++`) using this golfed prime checker and returning an anonymous infinite generator

```
from itertools import*
(x for x in map(lambda n:1+3*n**2//4,count(2)) if all(x%j for j in range(2,x)))

```

Try it online!

* mypetlion **-2** because arguably anonymous generators are more allowed than named ones
* **-6** by starting `count` at 2 +1 so that the `and x>1` in the prime checker I borrowed is unnecessary -7
> 1 votes

# Answer
# Japt, ~~14~~ 13 bytes

Adapted from Arnauld's formula. 1-indexed.

```
@µXj}f@Ò(X²*¾

```

Try it

1 byte saved thanks to EmbodimentOfIgnorance.
> 1 votes

# Answer
# Racket, 124 bytes

```
(require math)(define(f n[i 3])(let([t(+(exact-floor(* 3/4 i i))1)][k(+ 1 i)])(if(prime? t)(if(= 0 n)t(f(- n 1)k))(f n k))))

```

Try it online!

Returns the n-th cuban prime, 0-indexed.

Uses the formula of @Arnauld's JavaScript answer
> 1 votes

# Answer
# Whitespace, 180 bytes

```
[S S S T    S N
_Push_2][S N
S _Duplicate][N
S S N
_Create_Label_OUTER_LOOP][S N
N
_Discard_top_stack][S S S T N
_Push_1][T  S S S _Add][S N
S _Duplicate][S N
S _Duplicate][T S S N
_Multiply][S S S T  T   N
_Push_3][T  S S N
_Multiply][S S S T  S S N
_Push_4][T  S T S _Integer_divide][S S S T  N
_Push_1][T  S S S _Add][S S S T N
_Push_1][S N
S _Duplicate_1][N
S S S N
_Create_Label_INNER_LOOP][S N
N
_Discard_top_stack][S S S T N
_Push_1][T  S S S _Add][S N
S _Duplicate][S N
S _Duplicate][S T   S S T   T   N
_Copy_0-based_3rd][T    S S T   _Subtract][N
T   S T N
_Jump_to_Label_PRINT_if_0][S T  S S T   S N
_Copy_0-based_2nd][S N
T   _Swap_top_two][T    S T T   _Modulo][S N
S _Duplicate][N
T   S S S N
_Jump_to_Label_FALSE_if_0][N
S N
S N
_Jump_to_Label_INNER_LOOP][N
S S T   N
_Create_Label_PRINT][T  N
S T _Print_as_integer][S S S T  S T S N
_Push_10_(newline)][T   N
S S _Print_as_character][S N
S _Duplicate][N
S S S S N
_Create_Label_FALSE][S N
N
_Discard_top_stack][S N
N
_Discard_top_stack][N
S N
N
_Jump_to_Label_OUTER_LOOP]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Outputs newline-delimited indefinitely.

Try it online (with raw spaces, tabs, and new-lines only).

**Explanation in pseudo-code:**

Port of my Java 8 answer, which also uses the formula from *@Arnauld*'s JavaScript answer: \\$p\_n=\left\lfloor\frac{3n^2}{4}\right\rfloor+1,\\;n\ge3\\$.

```
Integer i = 2
Start OUTER_LOOP:
  i = i + 1
  Integer n = i*i*3//4+1
  Integer x = 1
  Start INNER_LOOP:
    x = x + 1
    If(x == n):
      Call function PRINT
    If(n % x == 0):
      Go to next iteration of OUTER_LOOP
    Go to next iteration of INNER_LOOP

function PRINT:
  Print integer n
  Print character '\n'
  Go to next iteration of OUTER_LOOP

```
> 1 votes

# Answer
# Python 3, 83 bytes

prints the cuban primes forever.

```
P=k=1
while 1:P*=k*k;x=k;k+=1;P%k>0==((x/3)**.5%1)*((x/3+.25)**.5%1-.5)and print(k)

```

Try it online!

Based on this prime generator. For every prime it checks whether an integer y exists that fulfills the equation for either \\$x = 1+y\\$ or \\$x=2+y\\$.

$$ p=\frac{(1+y)^3-y^3}{(1+y)-y} = 1 + 3y +3y^2 \Leftrightarrow y = -\frac{1}{2}\pm\sqrt{\frac{1}{4}+\frac{p-1}{3}}$$

$$ p=\frac{(2+y)^3-y^3}{(1+y)-y} = 4 + 6y +3y^2 \Leftrightarrow y = -1 \pm\sqrt{\frac{p-1}{3}}$$ As we only care whether \\$y\\$ has an integer solution, we can ignore the \\$\pm\\$ and \\$-1\\$.
> 1 votes

# Answer
# Perl 6, ~~33~~ 31 bytes

*-2 bytes thanks to Grimy*

```
{grep &is-prime,1+|¾*$++²xx*}

```

Try it online!

Anonymous code block that returns a lazy infinite list of Cuban primes. This uses Arnauld's formula to generate possible cuban primes, then `&is-prime` to filter them.

### Explanation:

```
{                           }  # Anonymous code block
 grep &is-prime,               # Filter the primes from
                         xx*   # The infinite list
                   ¾*          # Of three quarters
                     $++²      # Of an increasing number squared
                1+|            # Add one by ORing with 1

```
> 1 votes

# Answer
# Pari/GP, 51 bytes

Using Arnauld's formula.

```
n->a=0;for(i=1,n,until(isprime(p=3*a^2\4+1),a++));p

```

Try it online!
> 0 votes

# Answer
# APL(NARS), 98 chars, 196 bytes

```
r←h w;y;c;v
r←c←y←0⋄→4
→3×⍳∼0πv←1+3×y×1+y+←1⋄r←v⋄→0×⍳w≤c+←1
→2×⍳∼0πv+←3×y+1⋄c+←1⋄r←v
→2×⍳w>c

```

indented :

```
r←h w;y;c;v
r←c←y←0⋄→4
    →3×⍳∼0πv←1+3×y×1+y+←1⋄r←v⋄→0×⍳w≤c+←1
    →2×⍳∼0πv+←3×y+1⋄c+←1⋄r←v
    →2×⍳w>c

```

test:

```
  h ¨1..20
7 13 19 37 61 109 127 193 271 331 397 433 547 631 769 919 1201 1453 1657 1801
  h 1000
25789873
  h 10000
4765143511

```

it is based on: if y in N, one possible Cuban Prime is

```
S1=1+3y(y+1)

```

the the next possible Cuban Prime will be

```
S2=3(y+1)+S1

```
> 0 votes

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