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

1 Answer

0 votes
using System;

class Program
{
    // Function to check if a number is prime
    static bool IsPrime(int n) {
        if (n < 2) return false;
        if (n % 2 == 0) return n == 2;

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

    // Function to check if all digits are unique
    static bool HasUniqueDigits(int n) {
        bool[] seen = new bool[10]; // track digits 0–9

        while (n > 0) {
            int d = n % 10;
            if (seen[d]) return false; // duplicate found
            seen[d] = true;
            n /= 10;
        }
        
        return true;
    }

    static void Main()
    {
        for (int num = 1000; num <= 9999; num++) {
            if (IsPrime(num) && HasUniqueDigits(num)) {
                Console.WriteLine($"First 4-digit prime with all unique digits: {num}");
                return; // stop after finding the first one
            }
        }

        Console.WriteLine("No such number found.");
    }
}



/*
run:

First 4-digit prime with all unique digits: 1039

*/

 



answered 19 hours ago by avibootz
...