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

1 Answer

0 votes
#include <iostream>
#include <cmath>
#include <set>

// Function to check if a number is prime
bool isPrime(int n) {
    if (n < 2) return false;
    if (n % 2 == 0) return n == 2;
    
    int limit = 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
bool hasUniqueDigits(int n) {
    std::set<int> digits;
    
    while (n > 0) {
        int d = n % 10;
        if (digits.count(d)) return false; // duplicate found
        digits.insert(d);
        n /= 10;
    }
    
    return true;
}

int main() {
    for (int num = 1000; num <= 9999; num++) {
        if (isPrime(num) && hasUniqueDigits(num)) {
            std::cout << "First 4-digit prime with all unique digits: " << num << std::endl;
            return 0; // stop after finding the first one
        }
    }
    
    std::cout << "No such number found." << std::endl;
}



/*
run:

First 4-digit prime with all unique digits: 1039

*/

 



answered 21 hours ago by avibootz
...