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.

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

24 Answers 24

12
\$\begingroup\$

05AB1E, 8 bytes

Code:

μN1åNp*1⁄2

Explanation:

μ # Run this until the counting variable has reached the input value.
 N1å # 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).
 1⁄2 # If true, increment the counting variable.
 # After the loop, the stack is empty and implicitly prints N.

Uses CP-1252 encoding. Try it online!.

answered May 22, 2016 at 19:37
\$\endgroup\$
10
\$\begingroup\$

Pyth - 11 bytes

e.f&P_Z}`Q`

Test Suite.

answered May 22, 2016 at 18:23
\$\endgroup\$
9
\$\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.

answered May 22, 2016 at 19:40
\$\endgroup\$
7
\$\begingroup\$

Bash, 27 bytes

primes 0|grep 1ドル|sed 1ドルq\;d

primes comes from bsdgames.

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

answered May 22, 2016 at 18:48
\$\endgroup\$
5
\$\begingroup\$

Jelly, 13 bytes

×ばつÆP,3Dœṣ/Ṗμ#Ṫ

Try it online!

answered May 22, 2016 at 19:23
\$\endgroup\$
4
\$\begingroup\$

Mathematica, 75 bytes

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

May still be golfable.

answered May 22, 2016 at 19:41
\$\endgroup\$
1
  • \$\begingroup\$ This is probably the fastest solution since it uses NextPrime :) \$\endgroup\$ Commented May 24, 2016 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);
 }
}
answered May 23, 2016 at 7:21
\$\endgroup\$
1
  • \$\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\$ Commented May 23, 2016 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
}
answered May 22, 2016 at 18:35
\$\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!

answered May 22, 2016 at 21:19
\$\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 
answered May 22, 2016 at 18:28
\$\endgroup\$
2
\$\begingroup\$

Pyke, 15 bytes

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

Try it here!

answered May 22, 2016 at 18:48
\$\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
}
answered May 23, 2016 at 9:09
\$\endgroup\$
4
  • \$\begingroup\$ seq 1e20|factor|grep -Po "(?<=: )\d*2ドル\d$"|sed 1ドルq\;d \$\endgroup\$ Commented May 23, 2016 at 23:23
  • \$\begingroup\$ @DigitalTrauma, my brain does not work this way ;-) \$\endgroup\$ Commented May 24, 2016 at 6:38
  • \$\begingroup\$ Does it need the newlines? \$\endgroup\$ Commented May 24, 2016 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\$ Commented May 25, 2016 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:<Pn> = ->$n {grep({.is-prime&&/$n/},2..*)[$n-1]}
my @test = (
 1 => 11,
 2 => 23,
 3 => 23,
 10 => 1033,
);
plan +@test;
for @test {
 is Pn.key, .value, .gist
}
1..4
ok 1 - 1 => 11
ok 2 - 2 => 23
ok 3 - 3 => 23
ok 4 - 10 => 1033
answered May 23, 2016 at 16:01
\$\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.

answered May 23, 2016 at 10:21
\$\endgroup\$
2
  • 1
    \$\begingroup\$ you can replace && with & and remove ? from your regexp. \$\endgroup\$ Commented May 23, 2016 at 11:07
  • \$\begingroup\$ @cliffroot Thanks, edited the post. I always forget about && and & for some reason.. \$\endgroup\$ Commented May 23, 2016 at 11:12
1
\$\begingroup\$

Japt -h, (削除) 15 (削除ここまで) (削除) 13 (削除ここまで) 11 bytes

_j ©ZsèU}jU

Try it

answered Jan 12, 2018 at 16:01
\$\endgroup\$
0
1
\$\begingroup\$

Husk, 10 bytes

!fo`€d1dİp

Try it online!

Explanation

!fo`€d1dİp
 fo İp filter the infinite list of primes by the following:
 d1 are the digits of n
 `€ a sublist of('`' switches the arguments)
 d the digits of the number?
! get nth element
answered Jan 23, 2021 at 6:01
\$\endgroup\$
1
\$\begingroup\$

Stax, (削除) 14 (削除ここまで) 13 bytes

éâ^^εîï5~8<IM

Run and debug it

A good question for a generator.

-1 byte from recursive.

Explanation

Z{|p_$yI^*}{gnH input: single number, n
 n generator mode: count(stops after n values are found)
Z push a 0 under the input(start value)
 { } filter block:
 |p number is prime?
 * and
 _$ string representation of number
 yI^ contains n?
 {g generator block:
 implicit increment to get next number
 H get last generated value
answered Jan 23, 2021 at 6:17
\$\endgroup\$
1
\$\begingroup\$

Haskell, 97 bytes

import Data.List
p n=[z|z<-[2..],all((>0).mod z)[2..z-1],show n`elem`subsequences(show z)]!!(n-1)

Try it online!

"subsequences" is an annoyingly long word. Thanks to @xnor for saving a byte.

answered Aug 22, 2022 at 20:58
\$\endgroup\$
2
  • 1
    \$\begingroup\$ It looks like you have a stray space before the | \$\endgroup\$ Commented Aug 22, 2022 at 21:07
  • \$\begingroup\$ @xnor Thanks for spotting that I'd left that in; I had to add it because my IDE thought the list comprehension was a quasiquote without the space (probably a bug, now I think about it). \$\endgroup\$ Commented Aug 22, 2022 at 21:12
1
\$\begingroup\$

Vyxal, 8 bytes

‹Þp'?c;i

Try it Online!

answered Aug 22, 2022 at 21:28
\$\endgroup\$
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

answered May 23, 2016 at 10:25
\$\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
answered May 24, 2016 at 5:06
\$\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.

answered May 23, 2016 at 14:42
\$\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×ばつ⍳(w≤i)∧k←∨/s⍷⍕r⋄r←1πr⋄i+←k⋄→2
∇
 f ̈1 2 3 10 20 100
11 23 23 1033 4201 100999 
answered Mar 17, 2019 at 16:36
\$\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.

answered Oct 21, 2019 at 16:17
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.