Skip to content

Instantly share code, notes, and snippets.

@shubhendrapatel
Created January 5, 2017 12:18
Show Gist options
  • Select an option

  • Save shubhendrapatel/7e607d798fdb9c306005e88c18561813 to your computer and use it in GitHub Desktop.

Select an option

Save shubhendrapatel/7e607d798fdb9c306005e88c18561813 to your computer and use it in GitHub Desktop.
Generating primes efficiently in java
import java.util.*;
class finding_prime{
//For storing primes
static ArrayList<Integer> primes = new ArrayList<>();
//Checking number is prime or not
static boolean isPrime(Integer number){
//for itrating through primes list
ListIterator theItretor = primes.listIterator();
//loop through list and and checking against all primes
while(theItretor.hasNext()){
Object prime = theItretor.next();
if((number % Integer.parseInt(prime.toString())) == 0){
return false;
}
}
return true;
}
//Main method
public static void main(String[] args) {
int maxCount = Integer.parseInt(args[0]);//No of primes no is needed
/*
Start finding prime number from 2 since 2 is first prime number and
their is no prime number before that.
*/
for(int i = 2; i <= maxCount; i++){
//if(i is 2 ) add it to array since it is a prime
if(i == 2){
primes.add(2);
}
//If not 2 then check is prime or not
else if(isPrime(i)){
primes.add(i);
}
}
System.out.println("Their are/is "+primes.size()+" primes here is the list");
System.out.println();
System.out.println(primes);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment