Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

You will need to generate the smallest prime with n digits, and it will only contain digits specified in the list k.

Examples:

Input:

4
1 2

For this, you must generate the smallest prime with 4 digits, and that prime must only contain the digits 1 and 2.

Output:

2111

Input:

10
0 4 7 

Output:

4000000007

Input:

0
0 1 2 3 4 5

Output:


Input:

6
5 5 5 5 5 5 5 5 5 5 1 5 5 5 5 5 5 5 5 5 5

Output:

115151

You can guarantee that the input will always be in the format you specify, and you can do anything if you get invalid input (such as the input being a single digit n, without k.)

If no such solution to an input exists, your program is allowed to do any of the following:

  • Print banana
  • Throw an error
  • Run forever
  • Anything else

Since this is , try to aim for the shortest code.

The input can be in any format you specify. For example, if you want your input to be like any of the following, that is fine.

4
[1, 2]

[1,2]4

1,2
4

4 12

You can either write a program or a function, and it must either return the correct value or print it.

Whitespace is allowed anywhere.

This challenge inspired by A036229.

share|improve this question
1  
Mandatory question: Can we use any base? (The challenge is much easier in unary.) – flawr 12 hours ago
    
Can the solution have leading zeros if zero is one of the input digits? – Luis Mendo 12 hours ago
1  
@LuisMendo i wouldn't count that as 'proper' number, so no. – Okx 12 hours ago
6  
Shouldn't the second test case have 4000000007 as output? – Dennis 12 hours ago
1  
@busukxuan yes, of course. – Okx 4 hours ago

14 Answers 14

Bash + bsd-games package, 28

  • 18 bytes saved thanks to @Dennis.
primes 1|egrep -wm1 [$2]{$1}

Input given at the command-line as n followed by k as a non-delimited list of digits.

Try it online.

share|improve this answer
    
primes 1|grep -Pwm1 [$2]{$1} should work. tio.run/nexus/bash#@19QlJmbWqxgWJNelFqgoBtQnmuoEK1iFFutYlj7/‌​/9/… – Dennis 11 hours ago
    
@Dennis very good - thanks! BTW did you just add bsd-games to the TIO bash? When I tried a few minutes ago primes was not found. – Digital Trauma 11 hours ago
1  
Yes, I just added it. If anything is missing, just drop a message in talk.tryitonline.net. – Dennis 11 hours ago
    
This seems to be running forever: tio.run/nexus/bash#@19QlJmbWqxgWJOaXpRaoKBbnmuoEK1iFFutYlj7/‌​/9/… – Okx 2 hours ago

JavaScript (ES7), 100 bytes

Takes input as number of digits n and string of allowed digits s in currying syntax (n)(s). Returns undefined if no solution is found.

Works rather quickly for up to 6 digits, might work for 7 and definitely too slow -- and memory hungry -- beyond that.

n=>s=>(a=[...Array(10**n).keys()]).find(i=>eval(`/[${s}]{${n}}/`).test(i)&&a.every(j=>j<2|j==i|i%j))

Test

let f =

n=>s=>(a=[...Array(10**n).keys()]).find(i=>eval(`/[${s}]{${n}}/`).test(i)&&a.every(j=>j<2|j==i|i%j))
                                        
console.log(f(5)("247")) // 22247

share|improve this answer
    
Exactly what I would have done, except maybe with a different primality test. I'll see how my way compares to yours... – ETHproductions 12 hours ago
    
@ETHproductions I started with a recursive primality test but it would have limited it to 4 digits (or maybe a bit more on some browsers?) – Arnauld 12 hours ago
    
My first thought for a recursive solution is four bytes shorter, but it does throw an error for large numbers. I had n=>s=>[...Array(10**n).keys()].find(i=>eval(`/[${s}]{${n}}/`‌​).test(i)&(p=j=>i%--‌​j?p(j):j==1)(i)) – ETHproductions 12 hours ago
    
@ETHproductions I too was tempted to use & instead of &&. But performance wise, this is a very costly byte. – Arnauld 12 hours ago
    
The current version of Chrome supports TCO if you enable the "enable-javascript-harmony" flag (just go to chrome://flags and find that option) – ETHproductions 11 hours ago

Pyke, 18 16 bytes

j;~p#`ljqi`Q-!)h

Try it here!

Runs forever if no values found

share|improve this answer
    
@Okx should now be fast enough to run most if not all of the test cases now – muddyfish 12 hours ago
    
@Okx you know that you can download Pyke and run it offline if you want to test it fully without a time limit? – muddyfish 2 hours ago
    
Oh, sorry. I thought it was the code. Turns out the timeout is about four seconds which is not very much. – Okx 2 hours ago

Jelly, 12 bytes

DLׯP
ṗḌÇÐṀṂ

Takes a set and an integer as command-line arguments. Prints 0 if no solution exists.

Try it online!

How it works

ṗḌÇÐṀṂ  Main link. Left argument: A (digit set/array). Right argument: n (integer)

ṗ       Cartesian power; yield all arrays of length n that consist only of elements
        of the array A.
 Ḍ      Undecimal; convert all generated digit arrays to integers.
  ÇÐṀ   Keep only elements for which the helper link returns a maximal result.
     Ṃ  Take the minimum.


DLׯP   Helper link. Argument: k (integer)

D       Decimal; convert k into the array of its base 10 digits.
 L      Take the length.
   ÆP   Test if k is a prime number. Yields 1 or 0.
  ×     Multiply the length and the Boolean.
share|improve this answer
2  
Unless I'm completely misunderstanding the challenge, the correct result for 0,4,7 and 10 is 4000000007, not 4444444447. – Dennis 12 hours ago

Mathematica, 64 bytes

FirstCase[Tuples@##,x:{f_,___}/;f>0&&PrimeQ[y=FromDigits@x]:>y]&

Pure function where the first argument is the (sorted) list of allowed digits and the second argument is the allowed length. Tuples@## computes all lists of the allowed digits of the allowed length, then we find the FirstCase which matches x:{f_,___} such that the first digit f is not 0 and the integer y=FromDigits@x is prime and replaces it with y.

share|improve this answer
2  
That's cool how you use the /; test to select a tuple but also :> convert to the desired output format. (I see in the documentation that that's allowed, but only after reading this answer!) You should specify that your function requires the allowed digits to be sorted: it gives the wrong answer 3331 instead of 3313 if called with [{3,1},4]. – Greg Martin 11 hours ago
    
@ngenisis how about Select[FromDigits/@Tuples[Sort@#,#2],PrimeQ][[1]]&@@#& ? – martin 1 hour ago

JavaScript (ES6), 86 bytes

Takes input via the currying syntax, e.g., (4)('12')

n=>(d,F=(i,P=j=>i%--j?P(j):1==j)=>P(i)&&`${i}`.match(`^[${d}]{${n}}$`)?i:F(i+1))=>F(2)

'use strict';

const G=n=>(d,F=(i,P=j=>i%--j?P(j):1==j)=>P(i)&&`${i}`.match(`^[${d}]{${n}}$`)?i:F(i+1))=>F(2)

const submit = () => {
  console.clear();
  console.log(G(+n.value)(d.value));
}

button.onclick = submit;
submit();
<input id="n" type="number" min="1" value="4" />
<input id="d" type="text" value="12" />
<button id="button">Submit</button>

To be run in strict mode (for tail call optimisation [TCO]). If your environment doesn't support TCO it will result in a stack overflow error for primes larger than the environments stack.

For invalid inputs it will run forever.

Note:

  • Chrome (>= 51) users can go to chrome://flags/#enable-javascript-harmony and enable this flag to run the above snippet with TCO support.
  • Safari (>= 10) supports TCO
share|improve this answer
    
I think you can save two bytes with F=i=>(P=j=>i%--j?P(j):1==j)(i)&&... – ETHproductions 11 hours ago
    
@ETHproductions Can't because it has to be run in strict mode (to avoid stack overflow) and that creates a global variable P. – George Reith 11 hours ago
    
Oh, I didn't realize TCO only applied in strict mode. – ETHproductions 11 hours ago
    
@ETHproductions Aye neither did I until I read the spec I posted XD my first variation of the answer did use that shortcut until I realised it was invalid. – George Reith 11 hours ago

Python 2, 66 bytes

f=lambda n,s,k=1,p=1:10**~-n<p%k*k<s>=set(`k`)or-~f(n,s,k+1,p*k*k)

Try it online!

Takes input like f(3,{'9','3','8'}).

Python has no built-ins for primes, so the function generates them using Wilson's Theorem to check each potential value for k in turn for being prime.

The chained inequality 10**~-n<p%k*k<s>=set(`k`) combines three conditions on k:

  • 10**~-n<k: k contains at least n digits. We don't need to check exactly since if we reach more digits, there must have been no solution
  • p%k>0: k is prime, via the Wilson's Theorem condition with p=(n-1)!^2. Since p%k is 0 or 1, this can be combined with the previous condition as 10**~-n<p%k*k
  • s>=set(`k`): All digits in k are in the set s. This can be spliced in because Python 2 considers sets as bigger than numbers.

If the current k doesn't satisfy all of these, the function recurses onto k+1, adding 1 to the resulting output. Since the output terminates with True which equals 1, and k starts at 1, the output is k. This parallel tracking of k beats outputting k directly on success.

share|improve this answer

Perl 6, 43 bytes

->\n,@k {first *.is-prime&/^@k**{n}$/,^∞}

Runs forever if no solution exists.

share|improve this answer
    
what is the input format? – Okx 12 hours ago
1  
@Okx: It's a lambda that takes two argument: A number n, and a list k. – smls 12 hours ago

MATL, 17 bytes

wlwX"1GXNUStZp)l)

This function accepts two inputs, an integer specifying the number of digits and a character array indicating the possible values. In the case of no primes, an error is shown.

Try it Online!

Explanation

        % Implicitly grab two inputs. First as an integer (N), second as a string (OPTS)
w       % Reverse the order of the inputs
l       % Push the literal 1 to the stack
w       % Pull N back to the top of the stack
X"      % Repeat OPTS N times 
1G      % Explicitly grab N again
XN      % Get all N-character combinations of the repeated version of OPTS
U       % Convert each row from a string to a number
S       % Sort them in ascending order
tZp)    % Grab only those that are primes
l)      % Retrieve the first prime
        % Implicitly print the result
share|improve this answer

Pyth - 13 12 bytes

f&P_T!-Tz^Tt

Test Suite.

share|improve this answer

Sage, 62 bytes

lambda l,d:[p for p in primes(10^(l-1),10^l)if set(`p`)<=d][0]

Takes input of the form: f( 4 , {'1','2'} )

share|improve this answer

Brachylog, 15 bytes

tL∧?h~lṗ.dẹp⊆L∧

Try it online!

This is fairly slow.

Explanation

tL                Input = [H, L]
  ∧
   ?h~l .         The Output is a variable of length H
       ṗ.         The Output is a prime number
          ẹ       The Output's digits...
        .d        ...when removing duplicate digits...
           p      ...is a permutation...
            ⊆L    ...of an ordered subset of L
              ∧
share|improve this answer

Perl5, 77 bytes

($n,$d)=@ARGV;/^[$d]{$n}$/&&("x"x$_)!~/^(..+?)\1+$/&&print&&die for 2..10**$n

Run like this:

perl -le '($n,$d)=@ARGV;/^[$d]{$n}$/&&("x"x$_)!~/^(..+?)\1+$/&&print&&die for 2..10**$n' 4 12
share|improve this answer

Ruby, 77 76 bytes

->n,l{(10**~-n..10**n).find{|n|(2...n).none?{|x|n%x<1}&&!n.to_s[/[^#{l}]/]}}

Input format: a number and a string.

Example:

->n,l{...see above...} [6,"555555555515555555555"]
=> 115151
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.