Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- class BiggestPrimeNumber {
- /*
- Write a program that finds all prime numbers in the range 1 ... N. Use the Sieve of Eratosthenes algorithm.
- The program should print the biggest prime number which is <= N.
- Input
- On the first line you will receive the number N
- Output
- Print the biggest prime number which is <= N
- SIEVE PSEUDOCODE:
- input: an integer n > 1.
- output: all prime numbers from 2 through n.
- let A be an array of Boolean values, indexed by integers 2 to n, initially all set to true.
- for i = 2, 3, 4, ..., not exceeding √n do
- if A[i] is true
- for j = i2, i2+i, i2+2i, i2+3i, ..., not exceeding n do
- A[j] := false
- return all i such that A[i] is true.
- */
- public static int sieveOfEratosthenes(int n) {
- // Initializing the array and setting all values to true:
- boolean[] primes = new boolean[n + 1];
- Arrays.fill(primes, true);
- for (int i = 2; i <= Math.sqrt(n); i++) {
- // If primes[i] is not changed to false, then it is a prime:
- if (primes[i]) {
- // Update all multiples of p to false:
- for (int j = i * i; j <= n; j += i)
- primes[j] = false;
- }
- }
- // Iterating through the bool array backwards and returning the index of the first prime:
- for (int i = primes.length - 1; i >= 0; i--) {
- if (primes[i]) return i;
- }
- return 1;
- }
- }
- public class Main {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- System.out.print(BiggestPrimeNumber.sieveOfEratosthenes(scanner.nextInt()));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement