import java.util.*;
public class Primes{
public static void main(String args[]){
int integer;
Scanner scanner = new Scanner(System.in);
List<Integer> factors = new ArrayList<Integer>();
try{
System.out.print("\n\n\nEnter Integer : ");
integer = scanner.nextInt();
if(integer==0){
System.out.println("Error:Can not find primes for 0");
System.exit(-1);
}
for (Integer integer1 : Primes(integer)) {
System.out.print(integer1+"\t");
}
}catch(Exception e){
System.out.println("Error:Integer values must be given");
}
}
private static List<Integer> Primes(int integer){
List<Integer> factors = new ArrayList<Integer>();
for (int i = 1; i <= integer; i++) {
for(int j=2;j<=i;j++){
if(i==j){
factors.add(i);
break;
}
//value is not prime
if(i %j==0){
break;
}
}
}
return factors;
}
}
Using Sieve of Eratosthenes
About Sieve of Eratosthenes. This method is more faster than above prime number finding method.
import java.util.*;
//create a structure
class list{
int value;
char flag;
}
public class ex{
public static void main(String args[]){
int integer;
Scanner scanner = new Scanner(System.in);
try{
System.out.print("\n\n\nEnter Integer : ");
//get integer
integer = scanner.nextInt();
if(integer==0){
System.out.println("Error:Can not find primes for 0");
System.exit(-1);
}
PrimesSieveOfEratosthenes(integer);
}catch(Exception e){
System.out.println("Error:Integer values must be given");
}
}
private static void PrimesSieveOfEratosthenes(int integer){
list integers[]=new list[integer];
//initialize list elements
for(int m=0;m<integers.length;m++){
integers[m]=new list();
}
//add values to list elements
for(int i=1;i<integer;i++){
integers[i].value=i+1;
integers[i].flag='0';
}
//find prime numbers
for(int k=2;k<=integer;k++){
if(integers[k-1].flag=='0'){
for(int j=2*k-1;j<integer;j=j+k){
integers[j].flag='1';
}
}
}
//print prime numbers
for(int l=1;l<integer;l++){
if(integers[l].flag=='0'){
System.out.print(integers[l].value+"\t");
}
}
}
}
0 comments:
Post a Comment