For a given positive integers range, find the first and last prime number entirely composed of prime number digits, exceptionally including 0 (for the digits, a range of 0-2 should output 2-2). The range is inclusive. If no number is found, the expected output is 0. If there is only one such number, the expected output is that number twice.


  • For the range 1–100, the first prime number is 2 and the last is 73 (7 and 3 are prime numbers).
  • For the range 70–80, the first prime number is 73 and the last is also 73 (Since there is only one correct number in the given range, we return it twice).
  • For the range 190–200, there is no correct answer, so you return 0.
  • For the range 2000-2100, the first prime number is 2003 and the last is 2053 (we omit the digit 0, but all the other digits are prime)

This is , so the shortest code in bytes win!

All standard loopholes apply.


  • You are free to accept two integers as input however you may see fit, stack, function argument(s), CLI argument, stdin.
  • You must only receive two integers.


  • You must either return the result (a tuple, an array, multi-return if your language supports it), leave it on the stack, or print it (in this case, they must be separated somehow).
  • The order of the outputs is irrelevant.
  • You are allowed leading/trailing brackets and newlines.
  • You must return two numbers, if there is an answer, even if they are the same.
  • You must return 0 if there is no answer.
  • \$\begingroup\$ Just to make sure, if I'm returning a list of integers when there are answers, I can return a list containing just 0 when there are no answers? I don't need to return 0 instead of [0]? \$\endgroup\$ – Οurous Dec 18 '17 at 20:29

16 Answers 16


Python 2, 123 bytes

def f(a,b):r=[i for i in range(a,b+1)if(set(`i`)<=set('02357'))>any(i%k<1for k in range(3,i))];return len(r)and(r[0],r[-1])

Try it online!


Perl 6, 105 94 90 86 bytes

{my @b=grep {is-prime all($_,|.comb>>.Int Xor 2)},$^a..$^b;say @b??"@b[0] @b[*-1]"!!0}

JavaScript (ES6), 83 bytes

Takes the range [a-b] in currying syntax (a)(b). Returns either a 2-element array or 0.


Test cases

let f =




Mathematica, 91 bytes


Try it online!


Jelly, 14 bytes


Try it online!

How it works

æRµDo2ÆPẠµÐf.ị ~ Full program.

æR             ~ Inclusive prime range.
  µ      µÐf   ~ Only keep those which satisfy a condition.
   Do2ÆPẠ      ~ The filter condition:
   D             ~ The decimal digits of the current number.
    o2           ~ Logical or with 2 (maps 0 to 2 and any other digit to itself).
      ÆP         ~ Is prime (element-wise)?
        Ạ        ~ Check whether all the digits satisfy the condition.
            .ị ~ Get the element at modular index 0.5. Some details:
                 ~ Jelly is 1-indexed, so 1 gives us the first element, whilst 0
                   gives us the last element.
                 ~ If the ceil and the floor of the given number N don't match, 
                   then Jelly returns the items at indexes floor(N) and ceil(N).
                 ~ If the list is empty, this yields 0, hence it is very convenient.

If taking the whole range would be allowed (although I think it should not be), then 12 bytes:


Try it online!

  • \$\begingroup\$ 13 bytes Although it isn't super similar. Should I just post it myself? You can take it if you want but let me know if you're going to keep your solution. \$\endgroup\$ – dylnan Dec 13 '17 at 18:25
  • \$\begingroup\$ OP says For a given positive integers range. I'll ask to clarify \$\endgroup\$ – dylnan Dec 13 '17 at 18:27
  • \$\begingroup\$ @dylnan note that your version is invalid nonetheless (0 is the exception from the challenge, because it should be treated as a prime digit for some reason). Anyway, I posted a shorter and valid version \$\endgroup\$ – Mr. Xcoder Dec 13 '17 at 19:01
  • \$\begingroup\$ Oh I thought the 0 is prime rule had been changed \$\endgroup\$ – dylnan Dec 13 '17 at 19:11

Brachylog, 16 bytes


Try it online!

The completely non-sensical "return 0 if there's no prime" makes us lose 3 bytes (|∧0) for no reason (it would return false. if we didnt add them)


⟦₂                Range from the smallest element of the input to the biggest
  {   }ˢ          Select on that range:
   ṗ                Numbers that are primes
    ṗᵐ              And whose digits are primes
        ⟨   ⟩     Fork on this new list:
         ⌋          Minimum
           ⌉        maximum
          ≡         Do nothing and return [Minimum, Maximum]
             |∧0  If all of this fails (i.e. the list after selection is empty), return 0
  • \$\begingroup\$ Invalid because it doesn't handle the digit 0 as being prime (as specified in the challenge). Thus, it fails for [2000, 2100] \$\endgroup\$ – Mr. Xcoder Dec 18 '17 at 13:11

Pyth, 24 bytes

Using my initial approach turns out to be shorter.


Try it here!

(I was just updating to 23 but Steven beat me to it)


Try it here!

Natually, hM_BK can be replaced by ,hKeK.

25 bytes


Try it here!

26 bytes


Try it here!


Try it here!

How they work

.x,eKfP#I_M-+TjT;0}EQhKZ ~ Full program. Q, E = first, second inputs

.x                     Z ~ Try-catch block. If the code errors, output 0.
     f            }EQ    ~ Filter the range [E ... Q] for (uses a variable T):
            +TjT;          ~ Append T to the list of its digits.
           -     0         ~ Remove the zeros.
         _M                ~ Multiply each by -1 (for primality testing).
        I                  ~ Check if the result is invariant over...
      P#                   ~ Removing non-prime items.
    K                    ~ Assigned the filtered range to a variable K.
  ,e                     ~ Pair the last element of K with...
                     hK  ~ Its first element.

|>2.<f.AmP_|d2+TjT;*2}EQ1Z ~ Full program.

                   *2}EQ   ~ Inclusive range, repeated twice..
     f                     ~ Filter, using T as the current number.
                jT;        ~ Base-10 digits of T.
              +T           ~ Concatenated with T.
        mP_|d2             ~ Prime check after performing OR 2 (makes 0 be treated as prime)
      .A                   ~ Do all satisfy this condition?
   .<                   1  ~ Rotate by one place cyclically to the left.
 >2                        ~ Last two elements (ignored if there aren't enough)
|                        Z ~ Logical or with 0.
  • \$\begingroup\$ Outgolfed by 1, and I think there's still more to save \$\endgroup\$ – Steven H. Dec 18 '17 at 12:34
  • \$\begingroup\$ This one doesn't return two instances of [73] in the [70, 80] test case. \$\endgroup\$ – Steven H. Dec 18 '17 at 13:56
  • \$\begingroup\$ Outgolfed you back by 1, now at 25. \$\endgroup\$ – Steven H. Dec 18 '17 at 15:27
  • \$\begingroup\$ @StevenH. Outgolfed you back by 1, now at 24. \$\endgroup\$ – Mr. Xcoder Dec 18 '17 at 16:45
  • \$\begingroup\$ The competition's getting intense... at 23! \$\endgroup\$ – Steven H. Dec 18 '17 at 19:56

Mathematica 85 Bytes

I know there is already a similar answer, but the approach here is quite different.


This 83 character answer will paste and run in Mathematica. The TIO site doesn't know how to interpret ∞.


Jelly, 14 bytes


Try it online!

æRÇÐf.ị            Main link
æR                 Prime range
   Ðf              Filter the range with...
  Ç                The helper link
      ị            At index (decimal, returns [xs[floor], xs[ceil]], otherwise 0)
     .             0.5

Do2ÆPẠ             Helper link
D                  For each decimal
 o2                Replace 0s with 2s, an actual prime prime (could be 3, 5, or 7).
   ÆP              Filter primes (1 if true, 0 if false)
     Ạ             Check if all are true

Thanks to Erik the Outgolfer for the help fixing a bug. Thanks to Mr. Xcoder for the .ị trick.

  • \$\begingroup\$ Would ṙ-ḣ2 work for Ḣ,Ṫ to fix it (might have to modify a little more)? \$\endgroup\$ – Zacharý Dec 13 '17 at 15:27
  • \$\begingroup\$ @Zacharý that gives the output in the wrong order, though. And it doesn't seem to work :\ \$\endgroup\$ – Ven Dec 13 '17 at 15:29
  • \$\begingroup\$ @Mr.Xcoder The Jelly room led me to the same solution. Thanks! \$\endgroup\$ – Ven Dec 13 '17 at 15:50
  • \$\begingroup\$ .ị might work as well (kind of stolen from Mr. XCoder) \$\endgroup\$ – Zacharý Dec 13 '17 at 17:56
  • \$\begingroup\$ You're right! That's nice. \$\endgroup\$ – Ven Dec 14 '17 at 10:18

Ruby, 87 bytes


Try it online!


CJam, 36 bytes


Try it online!


Perl 6,  68 66 65 61  58 bytes


Try it


Try it


Try it


Try it

{($_=grep {.is-prime*!/<[14689]>/},$^a..$^b)??.[0,*-1]!!0}

Try it


{  # bare block lambda with two placeholder parameters 「$a」 and 「$b」

    $_ =  # store the list in 「$_」 for later use

      grep {

        *              # True * True == 1 (all others equal 0)

          !/<[14689]>/ # doesn't contain a non-prime other than 0

      $^a .. $^b       # inclusive Range

  )            # is the list Truish (not empty)
  ?? .[0,*-1]  # if so output the first and last values (from 「$_」)
  !! 0         # otherwise return 0

Perl 5, 79 + 2 (-ap) = 81 bytes

map{$f=0|sqrt;1while$_%$f--;$s||=$_,$\=-$_ if!$f&&!/[14689]/}$F[0]..$F[1];$_=$s

Try it online!


Java 8, 165 164 bytes

(a,b)->{for(;a<=b&!p(a);a++);for(;b>a&!p(b);b--);return a>b?"0":a+" "+b;}boolean p(int n){int N=n,i=2;for(;i<N;N=N%i++<1?0:N);return(n+"").matches("[02357]+")&N>1;}


Try it here.

(a,b)->{            // Method with two integer parameters and String return-type
                    //  (Input `a` is the lowest input, input `b` is the highest input)
  for(;a<=b         //  Increase `a` as long as it's smaller than or equal to `b`,
       &!p(a);a++); //   and it's not a prime, and not all of its digits are prime-digits
  for(;b>a          //  Decrease `b` as long as it's larger than `a`,
       &!p(b);b--); //   and it's not a prime, and not all of its digits are prime-digits
  return a>b?       //  If `a` is now larger than `b`:
    "0"             //   Return 0, because nothing is found
   :                //  Else:
    a+" "+b;}       //   Return the resulting `a` and `b`

boolean p(int n){int N=n,i=2;for(;i<N;N=N%i++<1?0:N);return(n+"").matches("[02357]+")&N>1;}
                    // Separate method that returns whether the input integer is a prime,
                    //  and all of its digits are also primes (or 0)

Clean, 142 131 125 bytes

import StdEnv
@a b#l=[n\\n<-[a..b]|and[gcd p n<2&&or[c==k\\k<-:"02357"]\\p<-[1..n-1],c<-:toString n]]
|l>[]=[hd l,last l]=[0]


import StdEnv
fn start finish
    # primes
        = [ n
            n <- [start..finish]
            | and [ gcd p n == 1 && isMember c ['0','2','3','5','7'] 
                p <- [1..n-1],
                c <-: toString n
    | isEmpty primes
        = [0]
    = [hd primes, last primes]

Try it online!


Pyth, 28 25 23 bytes

.xhM_BfP#I_M #+TjT;}FQ0

Test suite. Returns [2003,2053] for the last test case, since 2053 is prime.

  • \$\begingroup\$ Haha, invalid. Returns [0, 0] instead of 0 \$\endgroup\$ – Mr. Xcoder Dec 18 '17 at 19:57
  • \$\begingroup\$ Ah, shoot. I'll fix that. \$\endgroup\$ – Steven H. Dec 18 '17 at 19:59
  • \$\begingroup\$ @Mr.Xcoder Fixed! \$\endgroup\$ – Steven H. Dec 18 '17 at 20:48
  • \$\begingroup\$ God damn it I was just updating with 23 too \$\endgroup\$ – Mr. Xcoder Dec 18 '17 at 20:51
  • \$\begingroup\$ I thought you said you were going to bed... You tricky you :P \$\endgroup\$ – Steven H. Dec 18 '17 at 20:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.