Advertisement
Guest User

Untitled

a guest
Jun 28th, 2021
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.78 KB | None | 0 0
  1. import java.util.*;
  2.  
  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.         // Initializing the array and setting all values to true:
  30.         boolean[] primes = new boolean[n + 1];
  31.         Arrays.fill(primes, true);
  32.  
  33.         for (int i = 2; i <= Math.sqrt(n); i++) {
  34.             // If primes[i] is not changed to false, then it is a prime:
  35.             if (primes[i]) {
  36.                 // Update all multiples of p to false:
  37.                 for (int j = i * i; j <= n; j += i)
  38.                     primes[j] = false;
  39.             }
  40.         }
  41.  
  42.         // Iterating through the bool array backwards and returning the index of the first prime:
  43.         for (int i = primes.length - 1; i >= 0; i--) {
  44.             if (primes[i]) return i;
  45.         }
  46.  
  47.         return 1;
  48.     }
  49. }
  50.  
  51. public class Main {
  52.     public static void main(String[] args) {
  53.         Scanner scanner = new Scanner(System.in);
  54.         System.out.print(BiggestPrimeNumber.sieveOfEratosthenes(scanner.nextInt()));
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement