39
\$\begingroup\$

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.

\$\endgroup\$
  • 2
    \$\begingroup\$ Is there an OEIS for this? It feels like there should be \$\endgroup\$ – MayorMonty May 22 '16 at 19:52
  • \$\begingroup\$ @SpeedyNinja Nope, I've already checked. \$\endgroup\$ – Adnan May 22 '16 at 19:54
  • \$\begingroup\$ Related \$\endgroup\$ – Alex A. May 23 '16 at 15:26
  • 1
    \$\begingroup\$ I can't believe that this made it to number 5 on the Hot Network Questions list. \$\endgroup\$ – ericw31415 May 23 '16 at 15:51
  • \$\begingroup\$ A similar sequence \$\endgroup\$ – Nathan Merrill May 23 '16 at 18:56

20 Answers 20

12
\$\begingroup\$

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

\$\endgroup\$
10
\$\begingroup\$

Pyth - 11 bytes

e.f&P_Z}`Q`

Test Suite.

\$\endgroup\$
8
\$\begingroup\$

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.

\$\endgroup\$
6
\$\begingroup\$

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.

\$\endgroup\$
5
\$\begingroup\$

Jelly, 13 bytes

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

Try it online!

\$\endgroup\$
4
\$\begingroup\$

Mathematica, 75 bytes

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

May still be golfable.

\$\endgroup\$
  • \$\begingroup\$ This is probably the fastest solution since it uses NextPrime :) \$\endgroup\$ – user2542 May 24 '16 at 5:42
4
\$\begingroup\$

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);
    }
}
\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – Kevin Cruijssen May 23 '16 at 10:25
3
\$\begingroup\$

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
}
\$\endgroup\$
3
\$\begingroup\$

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!

\$\endgroup\$
3
\$\begingroup\$

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 
\$\endgroup\$
2
\$\begingroup\$

Pyke, 15 bytes

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

Try it here!

\$\endgroup\$
1
\$\begingroup\$

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
}
\$\endgroup\$
  • \$\begingroup\$ seq 1e20|factor|grep -Po "(?<=: )\d*$2\d$"|sed $1q\;d \$\endgroup\$ – Digital Trauma May 23 '16 at 23:23
  • \$\begingroup\$ @DigitalTrauma, my brain does not work this way ;-) \$\endgroup\$ – rexkogitans May 24 '16 at 6:38
  • \$\begingroup\$ Does it need the newlines? \$\endgroup\$ – ericw31415 May 24 '16 at 23:47
  • \$\begingroup\$ 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. \$\endgroup\$ – rexkogitans May 25 '16 at 7:42
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ you can replace && with & and remove ? from your regexp. \$\endgroup\$ – cliffroot May 23 '16 at 11:07
  • \$\begingroup\$ @cliffroot Thanks, edited the post. I always forget about && and & for some reason.. \$\endgroup\$ – Kevin Cruijssen May 23 '16 at 11:12
0
\$\begingroup\$

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

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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 
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

Japt -h, 15 13 11 bytes

_j ©ZsèU}jU

Try it

\$\endgroup\$

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.