Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,971 questions

51,913 answers

573 users

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 Nov 20, 2025 by avibootz
...