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 code-golf, so lowest byte count wins.
If something is confusing, please leave a comment.
24 Answers 24
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!.
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.
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.
Mathematica, 75 bytes
Nest[NestWhile[b=NextPrime,b@#,!StringContainsQ@@ToString/@{#,a}&]&,1,a=#]&
May still be golfable.
-
\$\begingroup\$ This is probably the fastest solution since it uses NextPrime :) \$\endgroup\$user2542– user25422016年05月24日 05:42:13 +00:00Commented May 24, 2016 at 5:42
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);
}
}
-
\$\begingroup\$ Hi, welcome to PPCG! Two things to note, 1. You can remove two spaces at
P {andString[] s. And 2. you are currently only giving the output for10, but the code-golf challenge was to take an inputnand give the proper output based on that input. Also, you might find this interesting: Tips for golfing in Java. \$\endgroup\$Kevin Cruijssen– Kevin Cruijssen2016年05月23日 10:25:48 +00:00Commented May 23, 2016 at 10:25
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
}
Julia, (削除) 61 (削除ここまで) 60 bytes
f(n,k=0,m=1)=k<n&&f(n,k+isprime(m)contains("$m","$n"),m+1)+1
MATL, 18 bytes
`@YqVGVXf?3M]NG<]&
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
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
}
-
\$\begingroup\$
seq 1e20|factor|grep -Po "(?<=: )\d*2ドル\d$"|sed 1ドルq\;d\$\endgroup\$Digital Trauma– Digital Trauma2016年05月23日 23:23:02 +00:00Commented May 23, 2016 at 23:23 -
\$\begingroup\$ @DigitalTrauma, my brain does not work this way ;-) \$\endgroup\$rexkogitans– rexkogitans2016年05月24日 06:38:48 +00:00Commented May 24, 2016 at 6:38
-
\$\begingroup\$ Does it need the newlines? \$\endgroup\$ericw31415– ericw314152016年05月24日 23:47:29 +00:00Commented 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\$rexkogitans– rexkogitans2016年05月25日 07:42:25 +00:00Commented May 25, 2016 at 7:42
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
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);}}
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;}
Same as above, but with n as integer input and without the verbose class stuff.
-
1\$\begingroup\$ you can replace
&&with&and remove?from your regexp. \$\endgroup\$cliffroot– cliffroot2016年05月23日 11:07:06 +00:00Commented May 23, 2016 at 11:07 -
\$\begingroup\$ @cliffroot Thanks, edited the post. I always forget about
&&and&for some reason.. \$\endgroup\$Kevin Cruijssen– Kevin Cruijssen2016年05月23日 11:12:50 +00:00Commented May 23, 2016 at 11:12
Husk, 10 bytes
!fo`€d1dİp
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
Stax, (削除) 14 (削除ここまで) 13 bytes
éâ^^εîï5~8<IM
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
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)
"subsequences" is an annoyingly long word. Thanks to @xnor for saving a byte.
-
1\$\begingroup\$ It looks like you have a stray space before the
|\$\endgroup\$xnor– xnor2022年08月22日 21:07:38 +00:00Commented 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\$Benji– Benji2022年08月22日 21:12:01 +00:00Commented Aug 22, 2022 at 21:12
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
Actually, 16 bytes
;$╗`P$╜@íu`╓dP.X
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
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.
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
Add++, 36 bytes
L,5*2^RßÞPABDBJVB]dG€Ωezߣ*BZB]A1_$:
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.
Hot Network Questionslist. \$\endgroup\$