Guest User

Untitled

a guest
Jun 23rd, 2021
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.97 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.util.Arrays;
  3.  
  4. class BiggestPrimeNumber {
  5.     /**
  6.         Write a program that finds all prime numbers in the range 1 ... N. Use the Sieve of Eratosthenes algorithm.
  7.         The program should print the biggest prime number which is <= N.
  8.  
  9.         Input
  10.         On the first line you will receive the number N
  11.  
  12.         Output
  13.         Print the biggest prime number which is <= N
  14.  
  15.         SIEVE PSEUDOCODE:
  16.         input: an integer n > 1.
  17.         output: all prime numbers from 2 through n.
  18.  
  19.         let A be an array of Boolean values, indexed by integers 2 to n, initially all set to true.
  20.         for i = 2, 3, 4, ..., not exceeding √n do
  21.             if A[i] is true
  22.                 for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n do
  23.                     A[j] := false
  24.  
  25.         return all i such that A[i] is true.
  26.      **/
  27.  
  28.     public static int sieveOfEratosthenes(int n) {
  29.  
  30.         // Initializing the array and setting all values to true:
  31.         boolean[] primes = new boolean[n + 1];
  32.         Arrays.fill(primes, true);
  33.  
  34.         for (int i = 2; i <= Math.sqrt(n); i++) {
  35.             // If primes[i] is not changed to false, then it is a prime:
  36.             if (primes[i]) {
  37.                 // Update all multiples of p to false:
  38.                 for (int j = i * i; j <= n; j += i)
  39.                     primes[j] = false;
  40.             }
  41.         }
  42.  
  43.         // Transfer all primes into a new int array to get the biggest number from for output:
  44.         int[] primesArr = new int[n+1];
  45.         for (int i = 0; i < primes.length; i++) {
  46.             if (primes[i]) {
  47.                 primesArr[i] = i;
  48.             }
  49.         }
  50.         Arrays.sort(primesArr);
  51.         return primesArr[primes.length-1];
  52.     }
  53. }
  54.  
  55. public class Main {
  56.     public static void main(String[] args) {
  57.         Scanner scanner = new Scanner(System.in);
  58.         System.out.print(BiggestPrimeNumber.sieveOfEratosthenes(scanner.nextInt()));
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment