First and last prime numbers with prime digits of range

12

2

Challenge

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.

Examples

  • 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.

Input

  • 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.

Output

  • 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.

LamaDelRay

Posted 2017-12-13T13:21:30.063

Reputation: 237

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]? – Οurous – 2017-12-18T20:29:51.590

Answers

6

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!

ovs

Posted 2017-12-13T13:21:30.063

Reputation: 21 408

122 bytes in Python 3 – mbomb007 – 2017-12-13T20:27:08.980

5

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}

Ven

Posted 2017-12-13T13:21:30.063

Reputation: 3 382

4

JavaScript (ES6), 83 bytes

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

n=>g=(m,a=0)=>n>m?a:g(m-1,(P=d=>m%--d?P(d):d>1|/[14689]/.test(m))(m)?a:[m,a[1]||m])

Test cases

let f =

n=>g=(m,a=0)=>n>m?a:g(m-1,(P=d=>m%--d?P(d):d>1|/[14689]/.test(m))(m)?a:[m,a[1]||m])

console.log(f(1)(100))
console.log(f(70)(80))
console.log(f(190)(200))

Arnauld

Posted 2017-12-13T13:21:30.063

Reputation: 111 334

4

Mathematica, 91 bytes

If[(s=Select[Range@##,(p=PrimeQ)@#&&And@@((p@#||#<1)&/@IntegerDigits@#)&])!={},MinMax@s,0]&

Try it online!

J42161217

Posted 2017-12-13T13:21:30.063

Reputation: 15 931

3

Jelly, 14 bytes

æRµDo2ÆPẠµÐf.ị

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:

Do2,ÆPȦµÐf.ị

Try it online!

Mr. Xcoder

Posted 2017-12-13T13:21:30.063

Reputation: 39 774

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. – dylnan – 2017-12-13T18:25:14.143

OP says For a given positive integers range. I'll ask to clarify – dylnan – 2017-12-13T18:27:47.490

@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 – Mr. Xcoder – 2017-12-13T19:01:05.800

Oh I thought the 0 is prime rule had been changed – dylnan – 2017-12-13T19:11:25.910

3

Pyth, 24 bytes

Using my initial approach turns out to be shorter.

.x,eKfP#I_M-+TjT;0}EQhKZ

Try it here!

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

?KfP#I_M-+TjT;0}FQhM_BK0

Try it here!

Natually, hM_BK can be replaced by ,hKeK.

25 bytes

.x,eKf.AmP_|d2+TjT;}EQhKZ

Try it here!

26 bytes

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

Try it here!

|>2.<fP#I_M|R2+TjT;*2}EQ1Z

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.

Mr. Xcoder

Posted 2017-12-13T13:21:30.063

Reputation: 39 774

Outgolfed by 1, and I think there's still more to save – Steven H. – 2017-12-18T12:34:46.120

This one doesn't return two instances of [73] in the [70, 80] test case. – Steven H. – 2017-12-18T13:56:50.863

Outgolfed you back by 1, now at 25. – Steven H. – 2017-12-18T15:27:37.480

@StevenH. Outgolfed you back by 1, now at 24. – Mr. Xcoder – 2017-12-18T16:45:15.517

The competition's getting intense... at 23! – Steven H. – 2017-12-18T19:56:28.747

I am going to bed now, continuing this tomorrow evening ;D (though I think our solutions are slowly tending towards optimality) – Mr. Xcoder – 2017-12-18T20:22:07.160

3

Brachylog, 16 bytes

⟦₂{ṗṗᵐ}ˢ⟨⌋≡⌉⟩|∧0

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)

Explanation

⟦₂                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

Fatalize

Posted 2017-12-13T13:21:30.063

Reputation: 32 976

Invalid because it doesn't handle the digit 0 as being prime (as specified in the challenge). Thus, it fails for [2000, 2100] – Mr. Xcoder – 2017-12-18T13:11:40.633

2

Jelly, 14 bytes

Do2ÆPẠ
æRÇÐf.ị

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.

Ven

Posted 2017-12-13T13:21:30.063

Reputation: 3 382

Would ṙ-ḣ2 work for Ḣ,Ṫ to fix it (might have to modify a little more)? – Zacharý – 2017-12-13T15:27:54.990

@Zacharý that gives the output in the wrong order, though. And it doesn't seem to work :\ – Ven – 2017-12-13T15:29:56.547

@Mr.Xcoder The Jelly room led me to the same solution. Thanks! – Ven – 2017-12-13T15:50:17.997

.ị might work as well (kind of stolen from Mr. XCoder) – Zacharý – 2017-12-13T17:56:17.990

You're right! That's nice. – Ven – 2017-12-14T10:18:36.213

2

Mathematica 85 Bytes

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

MinMax@Cases[Range@##,x_/;PrimeQ@x&&DisjointQ@@IntegerDigits/@{x,14689}]/.{_,∞}->0&

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

Kelly Lowder

Posted 2017-12-13T13:21:30.063

Reputation: 3 225

1

Ruby, 87 bytes

->a,b{(z=(a..b).select{|x|(2...x).none?{|r|x%r<1}&&/[14689]/!~"%d"%x})[0]?(z.minmax):0}

Try it online!

G B

Posted 2017-12-13T13:21:30.063

Reputation: 11 099

1

CJam, 36 bytes

),>{mp},{s{_!\~mp|}%1-!},_{_0=\W=}0?

Try it online!

Ven

Posted 2017-12-13T13:21:30.063

Reputation: 3 382

1

Perl 6,  68 66 65 61  58 bytes

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

Try it

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

Try it

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

Try it

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

Try it

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

Try it

Expanded:

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

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

      grep {
          .is-prime

        *              # 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
}

Brad Gilbert b2gills

Posted 2017-12-13T13:21:30.063

Reputation: 12 713

1

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!

Xcali

Posted 2017-12-13T13:21:30.063

Reputation: 7 671

1

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;}

Explanation:

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)

Kevin Cruijssen

Posted 2017-12-13T13:21:30.063

Reputation: 67 575

1

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]

Ungolfed:

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!

Οurous

Posted 2017-12-13T13:21:30.063

Reputation: 7 916

1

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.

Steven H.

Posted 2017-12-13T13:21:30.063

Reputation: 2 841

Haha, invalid. Returns [0, 0] instead of 0 – Mr. Xcoder – 2017-12-18T19:57:12.820

Ah, shoot. I'll fix that. – Steven H. – 2017-12-18T19:59:51.493

@Mr.Xcoder Fixed! – Steven H. – 2017-12-18T20:48:54.970

God damn it I was just updating with 23 too

– Mr. Xcoder – 2017-12-18T20:51:15.857

I thought you said you were going to bed... You tricky you :P – Steven H. – 2017-12-18T20:52:04.500

I strived to outgolf you first, it’s just too fun :-) – Mr. Xcoder – 2017-12-18T20:52:32.087