Displaying All Prime Numbers from 1 to N Using Java with Code

Prime numbers are natural numbers greater than 1 that have no positive divisors other than 1 and themselves. In this article, we will explore how to display all prime numbers from 1 to a given number N using different techniques in Java. We will provide multiple code examples, each demonstrating a unique approach.

What is a Prime Number?

A prime number is defined as a number that cannot be formed by multiplying two smaller natural numbers. For example, the first few prime numbers are 2, 3, 5, 7, 11, etc.

Display prime number using a Simple Loop in Java

In this example, we will use a simple loop to check each number from 2 to N and determine if it is prime by checking divisibility.

public class PrimeNumbers {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number (N): ");
        int N = scanner.nextInt();

        System.out.println("Prime numbers from 1 to " + N + " are:");
        for (int num = 2; num <= N; num++) {
            boolean isPrime = true;
            for (int i = 2; i <= num / 2; i++) {
                if (num % i == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                System.out.print(num + " ");
            }
        }
        scanner.close();
    }
}

Explanation

  • We use a nested loop: the outer loop iterates through each number from 2 to N, while the inner loop checks if the current number is divisible by any number less than itself.
  • If it finds a divisor, it sets isPrime to false and breaks out of the loop.
  • If isPrime remains true, the number is printed as a prime.

Output

Prime number using a Simple Loop in Java

Display prime number using the Square Root Method in Java

This method optimizes the prime-checking process by reducing the range of numbers we need to check for divisibility. Instead of checking up to num/2, we can check up to the square root of num.

Code example

import java.util.Scanner;

public class DisplayPrimeNumbers {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number (N): ");
        int N = scanner.nextInt();

        System.out.println("Prime numbers from 1 to " + N + " are:");
        for (int num = 2; num <= N; num++) {
            boolean isPrime = true;
            for (int i = 2; i * i <= num; i++) { // Check up to sqrt(num)
                if (num % i == 0) {
                    isPrime = false;
                    break;
                }
            }
            if (isPrime) {
                System.out.print(num + " ");
            }
        }
        scanner.close();
    }
}

Explanation

  • The inner loop now checks divisibility only up to the square root of num using i * i <= num.
  • This significantly reduces the number of iterations required for larger values of N.

Output

Prime number using a Simple Loop in Sqrt root

Display prime number using the Sieve of Eratosthenes

The Sieve of Eratosthenes is an efficient algorithm for finding all primes up to a specified integer N. It works by iteratively marking the multiples of each prime starting from p=2.

import java.util.Scanner;

public class SieveOfEratosthenes {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number (N): ");
        int N = scanner.nextInt();

        boolean[] isPrime = new boolean[N + 1];
        for (int i = 2; i <= N; i++) {
            isPrime[i] = true; // Assume all numbers are prime initially
        }

        for (int p = 2; p * p <= N; p++) {
            if (isPrime[p]) { // If prime
                for (int multiple = p * p; multiple <= N; multiple += p) {
                    isPrime[multiple] = false; // Mark multiples as non-prime
                }
            }
        }

        System.out.println("Prime numbers from 1 to " + N + " are:");
        for (int i = 2; i <= N; i++) {
            if (isPrime[i]) {
                System.out.print(i + " ");
            }
        }
        scanner.close();
    }
}

Explanation

  • We create a boolean array isPrime[] where each index represents whether that number is prime.
  • Initially, we assume all numbers greater than or equal to p are prime.
  • For each prime p, we mark all its multiples as non-prime.

Output

Display Prime number SieveOfEratosthenes

Conclusion

In this article, we explored three different techniques for displaying all prime numbers from 1 to N in Java:

  • Simple Loop Method: A straightforward approach using nested loops.
  • Square Root Method: An optimized version that reduces unnecessary iterations.
  • Sieve of Eratosthenes: An efficient algorithm suitable for finding all primes up to larger values of N.

These methods demonstrate varying levels of complexity and efficiency in identifying prime numbers. You can choose any method based on your requirements and preferences! Happy coding!