How to find the first 4-digit prime number where all digits are unique in PHP

1 Answer

0 votes
function isPrime(int $n): bool {
    if ($n < 2) return false;
    if ($n % 2 === 0) return $n === 2;

    $limit = (int) sqrt($n);
    for ($i = 3; $i <= $limit; $i += 2) {
        if ($n % $i === 0) return false;
    }
    
    return true;
}

function hasUniqueDigits(int $n): bool {
    $digits = str_split((string)$n);
    
    return count($digits) === count(array_unique($digits));
}

for ($num = 1000; $num <= 9999; $num++) {
    if (isPrime($num) && hasUniqueDigits($num)) {
        echo "First 4-digit prime with all unique digits: $num\n";
        exit; // stop after finding the first one
    }
}

echo "No such number found.\n";



/*
run:

First 4-digit prime with all unique digits: 1039

*/

 



answered 18 hours ago by avibootz
...