Print the nth prime that contains n

39

1

This question will be a twist on finding the nth prime number.

Challenge

You must write a program that will take one input n, and output the nth prime number whose decimal representation contains the decimal representation of n as a subtring.

Confused? Here are some examples.

n=1
Primes: 2, 3, 5, 7, 11
                    ^1 first prime that contains a 1
Output: 11

n=2
Primes: 2, 3, 5, 7, 11, 13, 17, 19, 23
        ^1                          ^2 second prime that contains a 2
Output: 23

n=3
Primes: 2, 3, 5, 7, 11, 13, 17, 19, 23
           ^1           ^2          ^3 third prime that contains a 3
Output: 23

n=10
Primes: 2, 3, 5, 7, 11, ..., 97, 101, 103, 107, 109, ..., 997, 1009, 1013, 1019, 1021, 1031, 1033
                                 ^1   ^2   ^3   ^4             ^5    ^6    ^7    ^8    ^9    ^10 tenth prime that contains a 10
Output: 1033

This is , so lowest byte count wins.

If something is confusing, please leave a comment.

ericw31415

Posted 2016-05-22T18:10:26.707

Reputation: 2 229

2Is there an OEIS for this? It feels like there should be – MayorMonty – 2016-05-22T19:52:46.043

@SpeedyNinja Nope, I've already checked. – Adnan – 2016-05-22T19:54:15.503

Related – Alex A. – 2016-05-23T15:26:20.433

1I can't believe that this made it to number 5 on the Hot Network Questions list. – ericw31415 – 2016-05-23T15:51:13.547

A similar sequence – Nathan Merrill – 2016-05-23T18:56:19.330

Answers

12

05AB1E, 8 bytes

Code:

µN¹åNp*½

Explanation:

µ          # Run this until the counting variable has reached the input value.
 N¹å       # Check if the input number is in the range variable.
    Np     # Check if the range variable is prime.
      *    # Multiply those two numbers (which is basically an AND operator).
       ½   # If true, increment the counting variable.
           # After the loop, the stack is empty and implicitly prints N.

Uses CP-1252 encoding. Try it online!.

Adnan

Posted 2016-05-22T18:10:26.707

Reputation: 41 965

10

Pyth - 11 bytes

e.f&P_Z}`Q`

Test Suite.

Maltysen

Posted 2016-05-22T18:10:26.707

Reputation: 25 023

8

Python 2, 67 65 62 bytes

f=lambda n,k=0,m=2,p=1:k/n or-~f(n,k+p%m*(`n`in`m`),m+1,p*m*m)

Test it on Ideone.

How it works

We use a corollary of Wilson's theorem:

corollary of Wilson's theorem

At all times, the variable p is equal to the square of the factorial of m - 1.

If k < n, k/n will yield 0 and f is called recursively. m is incremented, p is updated, and k is incremented if and only if m is a prime that contains n.

The latter is achieved by adding the result of p%m*(`n`in`m`) to k. By the corollary of Wilson's theorem if m is prime, p%m returns 1, and if not, it returns 0.

Once k reaches n, we found q, the nth prime that contains n.

We're in the next call during the check, so m = q + 1. k/n will return 1, and the bitwise operators -~ will increment that number once for every function call. Since it takes q - 1 calls to f to increment m from 2 to q + 1, the outmost call to f will return 1 + q - 1 = q, as intended.

Dennis

Posted 2016-05-22T18:10:26.707

Reputation: 196 637

6

Bash, 27 bytes

primes 0|grep $1|sed $1q\;d

primes comes from bsdgames.

Takes input as a command line argument, and outputs on STDOUT.

Doorknob

Posted 2016-05-22T18:10:26.707

Reputation: 68 138

5

Jelly, 13 bytes

×ÆP,³Dœṣ/Ṗµ#Ṫ

Try it online!

Dennis

Posted 2016-05-22T18:10:26.707

Reputation: 196 637

4

Mathematica, 75 bytes

Nest[NestWhile[b=NextPrime,b@#,!StringContainsQ@@ToString/@{#,a}&]&,1,a=#]&

May still be golfable.

LegionMammal978

Posted 2016-05-22T18:10:26.707

Reputation: 15 731

This is probably the fastest solution since it uses NextPrime :) – None – 2016-05-24T05:42:13.690

4

Java, 194 180 173 171 112 Bytes

Code:

a->{int i=1,j,n,r=0;for(j=n=new Integer(a);(r+=++i>=j&(""+j).contains(""+n)?1:0)!=n;j+=j%i==0?i=1:0);return j;}

Ungolfed:

class P{
    static int i=1,j,n,r;
    public static void main(String[]s) {
        for(
                j=n=new Integer(s[0]); //executes once before first iteration
                (r+=++i>=j&(""+j).contains(""+n)?1:0)!=n; //executes on first and every iteration
                j+=j%i==0?i=1:0 //executes after first and every iteration
           ) {
            ;
        }
        System.out.print(j);
    }
}

HopefullyHelpful

Posted 2016-05-22T18:10:26.707

Reputation: 208

Hi, welcome to PPCG! Two things to note, 1. You can remove two spaces at P { and String[] s. And 2. you are currently only giving the output for 10, but the code-golf challenge was to take an input n and give the proper output based on that input. Also, you might find this interesting: Tips for golfing in Java.

– Kevin Cruijssen – 2016-05-23T10:25:48.357

3

MATL, 18 bytes

`@YqVGVXf?3M]NG<]&

Try it online!

Explanation

This generates primes in order using a do...while loop. For each prime, the condition is tested (and the prime is consumed). If satisfied, that prime is pushed to the stack again. The number of elements in the stack is used as count of how many qualifying primes we have found. When there are enough of them, the last one is displayed.

`         % Do...while
  @       %   Push iteration index, k. Starts at 1
  YqV     %   k-th prime. Convert to string
  GV      %   Push input, n. Convert to string
  Xf      %   Find string within another
  ?       %   If non-empty
    3M    %     Push k-th prime again (increase stack size by 1)
  ]       %   End if
  NG<     %   Is stack size less than input number? If so proceeed with
          %   a new iteration; else exit do...while loop
]         % End do...while
&         % Implicitly display only top number in the stack 

Luis Mendo

Posted 2016-05-22T18:10:26.707

Reputation: 87 464

3

Ruby, 62 61 bytes

->i{Prime.lazy.map(&:to_s).grep(/#{i}/).first(i)[-1]}

Requires the -rprime flag (+8 bytes).

->i{            # lambda with one argument
Prime           # iterator over all primes
.lazy           # make the iterator lazy (can't evaluate infinite primes)
.map(&:x.to_s)  # convert the primes to strings
.grep(/#{i}/)   # find primes that regex match on the input (contain it)
.first(i)       # take the first (input) primes that satisfy this
[-1]            # take the last of those
}

Doorknob

Posted 2016-05-22T18:10:26.707

Reputation: 68 138

3

Julia, 61 60 bytes

f(n,k=0,m=1)=k<n&&f(n,k+isprime(m)contains("$m","$n"),m+1)+1

Try it online!

Dennis

Posted 2016-05-22T18:10:26.707

Reputation: 196 637

2

Pyke, 15 bytes

Q.fD_P.I`Q`R{(e

Try it here!

Blue

Posted 2016-05-22T18:10:26.707

Reputation: 26 661

1

Bash + GNU coreutils, 66 Bytes

In contrast to @Doorknob's solution, this one only needs things that are installed on every GNU/Linux:

for((n=2;;n++)){
[ `factor $n|wc -w` -eq 2 ]&&grep $1<<<$n&&exit
}

rexkogitans

Posted 2016-05-22T18:10:26.707

Reputation: 589

seq 1e20|factor|grep -Po "(?<=: )\d*$2\d$"|sed $1q\;d – Digital Trauma – 2016-05-23T23:23:02.197

@DigitalTrauma, my brain does not work this way ;-) – rexkogitans – 2016-05-24T06:38:48.283

Does it need the newlines? – ericw31415 – 2016-05-24T23:47:29.977

After for((...)){, there must be a space or newline, so it does not matter. Before the closing }, there must be a ; or a newline, so it does not matter either. – rexkogitans – 2016-05-25T07:42:25.827

1

Java 8, 192 183 181 171 bytes (full program)

interface M{static void main(String[]a){long n=new Long(a[0]),c=0,r=1,m,i;for(;c<n;c+=m>1&(r+"").contains(a[0])?1:0)for(m=++r,i=2;i<m;m=m%i++<1?0:m);System.out.print(r);}}

Try it online.

Explanation:

interface M{                    // Class
  static void main(String[]a){  //  Mandatory main-method
    long n=new Long(a[0]),      //   Input argument as number
         c=0,                   //   Counter, starting at 0
         r=1,                   //   Result-number, starting at 1
         m,i;                   //   Temp number
    for(;c<n;                   //   Loop as long as `c` does not equals `n`
        c+=                     //     After every iteration: increase `c` by:
           m>1                  //      If the current `r` is a prime,
           &(r+"").contains(a[0])?
                                //      and this prime contains the input `n`
            1                   //       Increase `c` by 1
           :                    //      Else:
            0)                  //       Leave `c` the same
      for(m=++r,                //    Increase `r` by 1 first with `++r`, and set `m` to it
          i=2;i<m;              //    Inner loop `i` in the range [2, `m`)
        m=m%i++<1?              //     If `m` is divisible by `i`
           0                    //      Change `m` to 0 (so it's not a prime)
          :                     //     Else:
           m);                  //      Leave `m` unchanged
    System.out.print(r);}}      //    Print `r` as result

Java 8, 105 bytes (lambda function)

n->{int c=0,r=1,m,i;for(;c<n;c+=m>1&(r+"").contains(n+"")?1:0)for(m=++r,i=2;i<m;m=m%i++<1?0:m);return r;}

Try it online.

Same as above, but with n as integer input and without the verbose class stuff.

Kevin Cruijssen

Posted 2016-05-22T18:10:26.707

Reputation: 67 575

1you can replace && with & and remove ? from your regexp. – cliffroot – 2016-05-23T11:07:06.687

@cliffroot Thanks, edited the post. I always forget about && and & for some reason.. – Kevin Cruijssen – 2016-05-23T11:12:50.640

1

Perl 6, 41 bytes

->$n {grep({.is-prime&&/$n/},2..*)[$n-1]}

Explanation:

-> $n { # has one parameter
  grep(
    {
      .is-prime # check that it is prime
      &&        # and
      / $n /    # that it contains the argument in the "string"
    },
    2 .. *      # for all numbers starting with 2
  )[ $n - 1 ]   # only take the $n-th one
                # ( accounting for 0 based array access )
}

Test:

#! /usr/bin/env perl6
use v6.c;
use Test;

my &prefix:<ℙ> = ->$n {grep({.is-prime&&/$n/},2..*)[$n-1]}

my @test = (
  1  => 11,
  2  => 23,
  3  => 23,
  10 => 1033,
);

plan +@test;

for @test {
  is ℙ.key, .value, .gist
}
1..4
ok 1 - 1 => 11
ok 2 - 2 => 23
ok 3 - 3 => 23
ok 4 - 10 => 1033

Brad Gilbert b2gills

Posted 2016-05-22T18:10:26.707

Reputation: 12 713

0

Japt -h, 15 13 11 bytes

_j ©ZsèU}jU

Try it

Shaggy

Posted 2016-05-22T18:10:26.707

Reputation: 24 623

0

APL(NARS), 39 chars, 78 bytes

{s←⍕w←⍵⋄2{(w≤⍵)∧k←∨/s⍷⍕⍺:⍺⋄(1π⍺)∇⍵+k}1}

1π is the next prime number...; test:

  f←{s←⍕w←⍵⋄2{(w≤⍵)∧k←∨/s⍷⍕⍺:⍺⋄(1π⍺)∇⍵+k}1}
  f¨1 2 3 10
11 23 23 1033 

but that already at 20 goes out the stack space... Instead this below seems ok even if has lenght a little more long (61 chars)

∇r←f w;i;k;s
r←2⋄s←⍕w⋄i←1
→0×⍳(w≤i)∧k←∨/s⍷⍕r⋄r←1πr⋄i+←k⋄→2
∇

  f¨1 2 3 10 20 100
11 23 23 1033 4201 100999 

RosLuP

Posted 2016-05-22T18:10:26.707

Reputation: 3 036

0

Add++, 36 bytes

L,5*2^RßÞPABDBJVB]dG€Ωezߣ*BZB]A1_$:

Try it online!

Fairly inefficient. Iterates over each integer \$i\$ such that \$i \le 25x^2\$ and filters out composites and primes that don't contain \$n\$. Finally, we take the \$n\$th value of the remaining integers.

caird coinheringaahing

Posted 2016-05-22T18:10:26.707

Reputation: 13 702

0

Clojure, 118 bytes

(defn s[n](nth(filter(fn[x](if(.contains(str x)(str n))(not-any? #(=(mod x %)0)(range 2 x))))(drop 2(range)))(dec n)))

Just gets the nth element of lazy infinite sequence of numbers which are prime and have n in their string representation.

You can try it here : https://ideone.com/ioBJjt

cliffroot

Posted 2016-05-22T18:10:26.707

Reputation: 1 080

0

PowerShell v2+, 108 99 bytes

Ooof. The lack of any sort of built-in prime calculation/checking really hurts here.

param($n)for(){for(;'1'*++$i-match'^(?!(..+)\1+$)..'){if("$i"-like"*$n*"){if(++$o-eq$n){$i;exit}}}}

Takes input $n, enters an infinite for() loop. Each iteration, we use a for loop wrapped around the PowerShell regex prime checker (h/t to Martin) to turn it into a prime generator by incrementing $i each time through the loop. (For example, running just for(){for(;'1'*++$i-match'^(?!(..+)\1+$)..'){$i}} will output 2, 3, 5, 7... separated by newlines).

Then a simple -like check to see if $n is somewhere in $i, and increment our counter $o. If we've reached where $n and $o are equal, output $i and exit. Otherwise we continue through the for to find the next prime and the process repeats.

AdmBorkBork

Posted 2016-05-22T18:10:26.707

Reputation: 41 581

0

Actually, 16 bytes

;$╗`P$╜@íu`╓dP.X

Try it online!

Explanation:

;$╗`P$╜@íu`╓dP.X
;$╗               make a copy of n, push str(n) to reg0
   `      `╓      push the first n values where f(k) is truthy, starting with k=0:
    P$              kth prime, stringified
      ╜@íu          1-based index of n, 0 if not found
            d     remove last element of list and push it to the stack (dequeue)
             P    nth prime
              .   print
               X  discard rest of list

Mego

Posted 2016-05-22T18:10:26.707

Reputation: 32 998