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

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

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

How to find the first and last 10‑digit prime numbers in Java

1 Answer

0 votes
public class TenDigitPrimes {

    /*
        This program finds:
            1. The first 10-digit prime number.
            2. The last 10-digit prime number.

        Approach:
        - Use long to safely hold 10-digit values.
        - Implement a primality test using trial division up to sqrt(n).
          This is efficient for checking individual numbers in this range.
        - Search upward from the smallest 10-digit number for the first prime.
        - Search downward from the largest 10-digit number for the last prime.
        - Skip even numbers to reduce unnecessary work.
    */

    // Check whether a number is prime
    public static boolean isPrime(long n) {
        if (n < 2) return false;
        if (n % 2 == 0) return n == 2;

        long limit = (long) Math.sqrt(n);
        for (long d = 3; d <= limit; d += 2) {
            if (n % d == 0) {
                return false;
            }
        }

        return true;
    }

    // Find the first 10-digit prime
    public static long first10DigitPrime() {
        long n = 1_000_000_000L; // smallest 10-digit number

        if (n % 2 == 0) {
            n++; // move to next odd number
        }

        while (!isPrime(n)) {
            n += 2; // check only odd numbers
        }

        return n;
    }

    // Find the last 10-digit prime
    public static long last10DigitPrime() {
        long n = 9_999_999_999L; // largest 10-digit number

        if (n % 2 == 0) {
            n--; // move to previous odd number
        }

        while (!isPrime(n)) {
            n -= 2; // check only odd numbers
        }
        
        return n;
    }

    public static void main(String[] args) {
        long first = first10DigitPrime();
        long last  = last10DigitPrime();

        System.out.println("First 10-digit prime: " + first);
        System.out.println("Last 10-digit prime:  " + last);
    }
}


/*
run:

First 10-digit prime: 1000000007
Last 10-digit prime:  9999999967

*/

 



answered 3 days ago by avibootz
...