Java 7、139 141バイト
long c(int a,String b){for(long n=2,i,x;;n++){for(x=n,i=2;i<x;x=x%i++<1?0:x);if(x>1&(n+"").length()==a&(n+"").matches("["+b+"]+"))return n;}}
32ビット以上の数をサポートすることにより+2バイト(変更int
しますlong
)
入力形式:整数(つまり4
)と文字列(つまり"12"
)
説明:
long c(int a, String b){ // Method with the two input parameters specified above
for(long n = 2, i, x; ; n++){ // Loop from 2 going upwards
for(x = n, i = 2; i < x; x = x % i++ < 1 ? 0 : x); // Prime check for `n`
if (x > 1 // if `n` is a prime (if `x` > 1 after the loop above it means `n` is a prime)
& (n+"").length() == a // AND if `n` has a length equal to the input integer
& (n+"").matches("["+b+"]+")){ // AND if `n` only contains the specified digits of the input String (using a regex)
return n; // Then we have our answer
}
} // If no answer is available for the given input, it continues looping
}
テストコード:
ここで試してみてください。
注:2番目のテストケースは非常に長い時間ループするため、無効になっています。
class M{
static long c(int a,String b){for(long n=2,i,x;;n++){for(x=n,i=2;i<x;x=x%i++<1?0:x);if(x>1&(n+"").length()==a&(n+"").matches("["+b+"]+"))return n;}}
public static void main(String[] a){
System.out.println(c(4, "12"));
//System.out.println(c(10, "047"));
System.out.println(c(6, "555555555515555555555"));
}
}
出力:
2111
115151