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
}
测试代码:
在这里尝试。
注意:第二个测试用例被禁用,因为它循环了很长时间。
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