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

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

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

Disclosure: My content contains affiliate links.

43,227 questions

56,129 answers

573 users

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

1 Answer

0 votes
public class UniquePrimeFinder {

    // Function to check if a number is prime
    public static boolean 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
    public static boolean hasUniqueDigits(int n) {
        boolean[] seen = new boolean[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;
    }

    public static void main(String[] args) {
        for (int num = 1000; num <= 9999; num++) {
            if (isPrime(num) && hasUniqueDigits(num)) {
                System.out.println("First 4-digit prime with all unique digits: " + num);
                return; // stop after finding the first one
            }
        }
        System.out.println("No such number found.");
    }
}



/*
run:

First 4-digit prime with all unique digits: 1039

*/

 



answered Nov 20, 2025 by avibootz
...