Monday 24 July 2017

Java Code to find the prime numbers using sieving algorithm

Problem:

It is possible to implement a sieving algorithm which crosses out each composite (non-prime) number exactly once rather than a number of times. The algorithm is based on the idea that any non-prime x can be written as x=p power k * q where k>= 1 and q is a prime >= p. Try to implement this algorithm.

Solution:

package com.myprograms;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class FindThePrimeNumber3 {
List<Boolean> input = new ArrayList<Boolean>();
List<Integer> resultList = new ArrayList<Integer>();
int n;

public static void main(String[] args) {
FindThePrimeNumber3 findThePrimeNumber2 = new FindThePrimeNumber3();
findThePrimeNumber2.getTheNumber();
findThePrimeNumber2.findPrimeNumbers();
findThePrimeNumber2.printTheResult();


}

public void getTheNumber(){
Scanner s = new Scanner(System.in);
System.out.println("Enter number : ");
n = s.nextInt();
input.add(Boolean.FALSE);
input.add(Boolean.FALSE);
for(int i = 2; i<= n; i++){
input.add(Boolean.TRUE);
}
s.close();
}

public void findPrimeNumbers(){
for (int i = 2; i*i <= n; i++) {
if(input.get(i)){
for(int j = i*2; j<= n; j = j+i){
input.set(j, Boolean.FALSE);
}
}
}
}

public void printTheResult(){
for(int i = 2; i < input.size(); i++){
if(input.get(i)){
resultList.add(i);
}
}
System.out.println("the prime numbers upto given number are " + resultList);
}

}


Output:

Enter number :
20
the prime numbers upto given number are [2, 3, 5, 7, 11, 13, 17, 19]


No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...