using
System;
class
Program
{
static
bool
TryComposite(
long
a,
long
d,
long
n,
int
s)
{
long
x = ModPow(a, d, n);
if
(x == 1 || x == n - 1) {
return
false
;
}
for
(
int
i = 0; i < s; i++) {
x = ModPow(x, 2, n);
if
(x == n - 1) {
return
false
;
}
}
return
true
;
}
static
long
ModPow(
long
baseNumber,
long
exponent,
long
modulus)
{
long
result = 1;
while
(exponent > 0) {
if
((exponent & 1) == 1) {
result = (result * baseNumber) % modulus;
}
baseNumber
= (baseNumber * baseNumber) % modulus;
exponent >>= 1;
}
return
result;
}
static
bool
IsProbablePrime(
long
n,
int
k)
{
if
(n == 0 || n == 1) {
return
false
;
}
if
(n == 2) {
return
true
;
}
if
(n % 2 == 0) {
return
false
;
}
long
d = n - 1;
int
s = 0;
while
(d % 2 == 0) {
s++;
d /= 2;
}
Random rnd =
new
Random();
for
(
int
i = 0; i < k; i++) {
long
a = rnd.Next(2, (
int
)n - 1);
if
(TryComposite(a, d, n, s)) {
return
false
;
}
}
return
true
;
}
static
long
LargestLeftTruncatablePrime(
int
baseNumber)
{
int
radix = 0;
long
[] candidates = { 0 };
while
(
true
) {
long
[] newCandidates =
new
long
[0];
long
multiplier
= (
long
)Math.Pow(baseNumber, radix);
for
(
int
i = 1; i < baseNumber; i++) {
for
(
int
j = 0; j < candidates.Length;
j++) {
if
(IsProbablePrime(
candidates[j] + i * multiplier,
30)) {
Array.Resize(
ref
newCandidates,
newCandidates.Length
+ 1);
newCandidates[newCandidates.Length
- 1]
= candidates[j]
+ i * multiplier;
}
}
}
if
(newCandidates.Length == 0) {
return
candidates[0];
}
candidates = newCandidates;
radix++;
}
}
static
void
Main(
string
[] args)
{
Console.WriteLine(LargestLeftTruncatablePrime(3));
}
}