Skip to content

Instantly share code, notes, and snippets.

@bjpeterdelacruz
Last active December 26, 2015 00:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjpeterdelacruz/7064075 to your computer and use it in GitHub Desktop.
Save bjpeterdelacruz/7064075 to your computer and use it in GitHub Desktop.
A Java program that will find all prime numbers between 0 and N.
import java.util.ArrayList;
/**
* This program finds all of the prime numbers between 0 and a number supplied by the user,
* inclusive.
*
* @author BJ Peter DeLaCruz
* @version 1.1
*/
public class CountingPrimeNumbers {
public static ArrayList<Integer> arrayList1;
public static ArrayList<Boolean> arrayList2;
public static void main(String[] args) {
// Check if only one argument is supplied,
// which is the upper bound for finding prime numbers.
if (args.length != 1) {
System.exit(1);
}
int num = Integer.parseInt(args[0]);
long startTime, endTime, aveTime = 0;
for (int j = 0; j < 10; j++) {
arrayList1 = new ArrayList<Integer>();
arrayList2 = new ArrayList<Boolean>();
// Populate the array list from 0 to upper bound.
for (int i = 0; i <= num; i++) {
arrayList1.add(new Integer(i));
arrayList2.add(new Boolean(true));
}
// Find all of the prime numbers between 0 and upper
// bound.
startTime = System.currentTimeMillis();
for (int i = 2; i <= num; i++) {
if (isBiggestPrime(arrayList1.get(i))) {
break;
}
}
endTime = System.currentTimeMillis();
aveTime += (endTime - startTime);
// Display the time it took to find all of the prime
// numbers from 0 to upper bound.
String runtime = (endTime - startTime) + " ms";
System.out.println("Run #" + j + ": " + runtime);
}
System.out.println("Average time: " + aveTime / 10 + " ms");
/*
* // Print all of the prime numbers from 0 to upper bound. for (int i = 2; i <= num; i++) { if
* (arrayList2.get(i)) { System.out.println(arrayList1.get(i)); } }
*/
}
private static boolean isBiggestPrime(int i) {
// If i*i is greater than the last element in the
// array list, stop finding prime numbers (all of
// the prime numbers have already been found).
if ((i * i) >= arrayList1.get(arrayList1.size() - 1)) {
return true;
}
getPrimeNumbers(i);
return false;
}
private static void getPrimeNumbers(int i) {
for (int j = i; j < arrayList1.size(); j++) {
// If the current element j being tested is
// divisible by i, then j is not a prime number.
if (j % i == 0 && j != i) {
arrayList2.set(j, false);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment