I am supposed to make a class PrimeNumberGenerator
which has a method nextPrime
that will print out all prime numbers up to a number the user input
Doing primality check on each and every number is inefficient in your case. Use Sieve_of_Eratosthenes instead, to find all prime numbers up to any given limit.
public class PrimeGenerator {
private final BitSet primes;
private int nextPrime = 0;
/**
* Sieve of Eratosthenes
*/
public PrimeGenerator(final int LIMIT)
{
primes = new BitSet(LIMIT+1);
primes.set(2, LIMIT);
for (int i = 4; i < LIMIT; i += 2)
primes.clear(i);
final int SQRT = (int) Math.sqrt(LIMIT);
for (int p = 3; p <= SQRT; p = primes.nextSetBit(p+2)) {
for (int j = p * p; j <= LIMIT; j += 2 * p) {
primes.clear(j);
}
}
}
public int nextPrime()
{
nextPrime = primes.nextSetBit(nextPrime + 1);
return nextPrime;
}
public static void main(String[] args) {
// print primes up to 1000
PrimeGenerator primeGen = new PrimeGenerator(50);
int prime = primeGen.nextPrime();
while (prime != -1) {
System.out.println(prime);
prime = primeGen.nextPrime();
}
}
}
Optimization tips when implementing Sieve of Eratosthenes:
Iterate only over the odd numbers. Because all the multiples of 2, except for 2 is composite.
Start eliminating from (p * p)
. So for instance for the prime number 3, you should start eliminating from 9.
Increment by 2 * p
instead of p, so to avoid even numbers.
This could generate millions of primes in just seconds.
public class PrimeNumberGeneration {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
ArrayList<Integer> primeNumbers = new ArrayList<Integer>();
primeNumbers.add(2);
System.out.println(2);
no_loop:
for(int no=3; no<=n; no+=2){
for(Integer primeNumber: primeNumbers){
if((no%primeNumber)==0){
continue no_loop;
}
}
primeNumbers.add(no);
System.out.println(no);
}
}
}
Here is my Soluction.
public class PrimeNumberGenerator {
public static void print(int n) {
// since 1 is not prime number.
for (int i = 2; i <= n; i++) {
if (isPrime(i)) {
System.out.print(i + "\n");
}
}
}
public static boolean isPrime(int num) {
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
print(10);
}
}
Output: 2 3 5 7