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 <stdio.h>
#include <math.h>

// Function to check if a number is prime
int isPrime(int n) {
    if (n < 2) return 0;
    if (n % 2 == 0) return n == 2;

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

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

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

int main(void) {
    for (int num = 1000; num <= 9999; num++) {
        if (isPrime(num) && hasUniqueDigits(num)) {
            printf("First 4-digit prime with all unique digits: %d\n", num);
            return 0; // stop after finding the first one
        }
    }

    printf("No such number found.\n");
    
    return 0;
}


 
/*
run:
   
First 4-digit prime with all unique digits: 1039
   
*/

 



answered Nov 20, 2025 by avibootz
...