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,846 questions

55,675 answers

573 users

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

1 Answer

0 votes
#include <iostream>
#include <cmath>
#include <cstdint>

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

    Strategy:
    - Use uint64_t to safely handle 10-digit values.
    - Implement a fast primality test using trial division up to sqrt(n).
      This is efficient for single-number checks in the 10-digit 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.
    - Check only odd numbers to reduce unnecessary work.

    The code is structured for clarity:
    - is_prime(...) performs primality testing.
    - first_10_digit_prime() finds the smallest 10-digit prime.
    - last_10_digit_prime() finds the largest 10-digit prime.
*/

// Determine whether a number is prime
bool is_prime(uint64_t n) {
    if (n < 2) return false;
    if (n % 2 == 0) return n == 2;

    uint64_t limit = static_cast<uint64_t>(std::sqrt(n));
    for (uint64_t d = 3; d <= limit; d += 2) {
        if (n % d == 0) {
            return false;
        }
    }
    
    return true;
}

// Find the first 10-digit prime
uint64_t first_10_digit_prime() {
    uint64_t n = 1'000'000'000ULL; // smallest 10-digit number

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

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

    return n;
}

// Find the last 10-digit prime
uint64_t last_10_digit_prime() {
    uint64_t n = 9'999'999'999ULL; // largest 10-digit number

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

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

    return n;
}

int main() {
    uint64_t first = first_10_digit_prime();
    uint64_t last  = last_10_digit_prime();

    std::cout << "First 10-digit prime: " << first << "\n";
    std::cout << "Last 10-digit prime:  " << last  << "\n";
}


/*
run:

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

*/

 



answered 4 days ago by avibootz
...