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

1 Answer

0 votes
function isPrime(n: number): boolean {
  if (n < 2) return false;
  if (n % 2 === 0) return n === 2;

  const limit: number = Math.floor(Math.sqrt(n));
  for (let i = 3; i <= limit; i += 2) {
    if (n % i === 0) return false;
  }
  
  return true;
}

function hasUniqueDigits(n: number): boolean {
  const digits: string = n.toString();
  const unique: Set<string> = new Set(digits);

  return unique.size === digits.length;
}

function main(): void {
  for (let num = 1000; num <= 9999; num++) {
    if (isPrime(num) && hasUniqueDigits(num)) {
      console.log(`First 4-digit prime with all unique digits: ${num}`);
      return; // stop after finding the first one
    }
  }
  console.log("No such number found.");
}

main();



/*
run:

"First 4-digit prime with all unique digits: 1039" 

*/

 



answered 8 hours ago by avibootz
...