From 0e0fcb5d2a5bd3721ba047c197b2fd60acf48f2c Mon Sep 17 00:00:00 2001 From: Raghav Bajaj <73180455+Raghav-Bajaj@users.noreply.github.com> Date: Tue, 31 Oct 2023 20:07:36 +0530 Subject: [PATCH] Update PrimeNumberGenerator.java optimizing primeNumberGenerator with sieve of Eratosthenes --- PrimeNumberGenerator.java | 54 +++++++++++---------------------------- 1 file changed, 15 insertions(+), 39 deletions(-) diff --git a/PrimeNumberGenerator.java b/PrimeNumberGenerator.java index 98c37dd8a16..b125ee3c95a 100644 --- a/PrimeNumberGenerator.java +++ b/PrimeNumberGenerator.java @@ -1,62 +1,38 @@ -import java.util.ArrayList; -import java.util.List; import java.util.Scanner; public class PrimeNumberGenerator { public static void main(String[] args) { Scanner sc = new Scanner(System.in); - System.out.print("Enter the start of the range: "); - int startRange = sc.nextInt(); - System.out.print("Enter the end of the range: "); int endRange = sc.nextInt(); - if (startRange > endRange) { - System.out.println("Invalid range. The start of the range should be less than or equal to the end."); - } else { - List primeNumbers = generatePrimesInRange(startRange, endRange); + boolean[] isPrime = sieveOfEratosthenes(endRange); - System.out.println("Prime numbers between " + startRange + " and " + endRange + ":"); - for (int prime : primeNumbers) { - System.out.print(prime + " "); + System.out.println("Prime numbers up to " + endRange + ":"); + for (int i = 2; i <= endRange; i++) { + if (isPrime[i]) { + System.out.print(i + " "); } } sc.close(); } - // Function to generate prime numbers within a specified range - public static List generatePrimesInRange(int start, int end) { - List primeNumbers = new ArrayList<>(); - - for (int num = start; num <= end; num++) { - if (isPrime(num)) { - primeNumbers.add(num); - } - } - - return primeNumbers; - } - - // Function to check if a number is prime - public static boolean isPrime(int num) { - if (num <= 1) { - return false; - } - if (num <= 3) { - return true; - } - if (num % 2 == 0 || num % 3 == 0) { - return false; + public static boolean[] sieveOfEratosthenes(int n) { + boolean[] isPrime = new boolean[n + 1]; + for (int i = 2; i <= n; i++) { + isPrime[i] = true; } - for (int i = 5; i * i <= num; i += 6) { - if (num % i == 0 || num % (i + 2) == 0) { - return false; + for (int p = 2; p * p <= n; p++) { + if (isPrime[p]) { + for (int i = p * p; i <= n; i += p) { + isPrime[i] = false; + } } } - return true; + return isPrime; } }