713591. Prime List

Medium

Prime List

Slug: prime-list--170646 Difficulty: Medium Id: 713591 Topic Tags: Linked List, Mathematical, Prime Number, Data Structures, Algorithms Company Tags: None

Summary

The problem involves generating a list of prime numbers. The key concept involved is the generation of prime numbers, which requires an understanding of mathematical concepts such as primality testing and sieve algorithms. The solution requires efficient data structures like linked lists to store and manipulate the prime numbers.

Detailed Explanation

To solve this problem, we will use the Sieve of Eratosthenes algorithm, a popular method for generating prime numbers. This algorithm works by iteratively marking the multiples of each prime number starting from 2. The multiples of a given prime are generated as a sequence of numbers: p, 2p, 3p, 4p, ...; these can be written in the form nk, where n is any positive integer, and k is the index of the multiple.

Here's a step-by-step breakdown of the solution:

  1. Initialize an array or linked list to store prime numbers.
  2. Start from 2 (the first prime number) and iterate until the desired limit.
  3. For each number i, check if it is a prime by iterating from 2 to sqrt(i) and checking if i is divisible by any of these numbers.
  4. If i is not divisible by any of these numbers, mark it as prime in the list.
  5. Continue this process until the desired limit is reached.

Time complexity: O(n log log n) due to the use of the Sieve of Eratosthenes algorithm. Space complexity: O(n) for storing the prime numbers in a linked list or array.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.ArrayList;
import java.util.List;

public class PrimeList {
    public static List<Integer> generatePrimes(int n) {
        boolean[] isPrime = new boolean[n + 1];
        for (int i = 2; i <= n; i++) {
            if (!isPrime[i]) {
                for (int j = i * i; j <= n; j += i) {
                    isPrime[j] = true;
                }
            }
        }
        List<Integer> primes = new ArrayList<>();
        for (int i = 2; i <= n; i++) {
            if (!isPrime[i]) {
                primes.add(i);
            }
        }
        return primes;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.