📜  SPOJ Prime1 - Java (1)

📅  最后修改于: 2023-12-03 15:20:12.174000             🧑  作者: Mango

SPOJ Prime1 - Java

Introduction

SPOJ Prime1 is a problem on the Sphere Online Judge (SPOJ) platform that requires you to generate prime numbers in a given range. This problem is commonly solved using the Sieve of Eratosthenes algorithm. In this guide, you will learn how to solve this problem using Java.

Problem Statement

The problem statement for SPOJ Prime1 is as follows:

You are given two integers, m and n (1 <= m <= n <= 10^9), and you need to find all prime numbers between m and n (both inclusive).

Approach

To solve this problem, we will be using the Sieve of Eratosthenes algorithm. The algorithm works by iteratively marking the multiples of each prime starting from 2, thus sieving out the composite numbers and leaving behind only the prime numbers.

The steps to solve this problem are as follows:

  1. Initialize a boolean array isPrime of size n+1 and set all values to true.
  2. Iterate from 2 to the square root of n:
    • If isPrime[i] is true, mark all multiples of i as false in the isPrime array.
  3. Iterate from m to n:
    • If isPrime[i] is true, add i to the result list of prime numbers.
  4. Return the result list.
Java Implementation

Here's the Java implementation for solving the SPOJ Prime1 problem:

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        int m = 2; // Starting range
        int n = 100; // Ending range

        List<Integer> primes = findPrimes(m, n);
        for (int prime : primes) {
            System.out.println(prime);
        }
    }

    public static List<Integer> findPrimes(int m, int n) {
        boolean[] isPrime = new boolean[n + 1];
        List<Integer> primes = new ArrayList<>();

        for (int i = 2; i <= n; i++) {
            isPrime[i] = true;
        }

        for (int i = 2; i * i <= n; i++) {
            if (isPrime[i]) {
                for (int j = i * i; j <= n; j += i) {
                    isPrime[j] = false;
                }
            }
        }

        for (int i = m; i <= n; i++) {
            if (isPrime[i]) {
                primes.add(i);
            }
        }

        return primes;
    }
}

Note: Update the values of m and n in the main method according to your requirements.

Conclusion

By implementing the Sieve of Eratosthenes algorithm, you can efficiently find all prime numbers in a given range. The Java solution provided above can be used to solve the SPOJ Prime1 problem and similar problems that require generating prime numbers. This algorithm has a time complexity of O(n log log n), where n is the input range.