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 19 hours ago by avibootz
...