Primzahlen(Java)

Aus IT074-Wiki

Wechseln zu: Navigation, Suche

Ermittlung durch Vektor

Kleine Java-Applikation zum Ermitteln von Primzahlen durch Vektor. (Bei Werten über 1mio kommt es zu OutOfMemoryError-Exceptions vom Java HeapSpace)

Source-Code: Prime.java

import java.util.Vector;
 
public class Prime {
 
	public static void main(String[] args) throws Exception {
 
		int max = Integer.parseInt(args[0]);
 
		Vector<Integer> vec = new Vector<Integer>();
		int calc = (int)Math.sqrt(max);
 
		for(int i = 1; i <= max; i++) {
			vec.add(i);
		}
 
		for(int i = 0; i < vec.size(); i++) {
 
			if(vec.elementAt(i) != 1) {
 
				if(vec.elementAt(i) > calc) break;
 
				for(int j = i+1; j < vec.size(); j++) {
					if(vec.elementAt(j)%vec.elementAt(i) == 0) {
						vec.remove(j);
					}
				}
			}
		}
 
		// Ausgabe
		for(int k = 0; k < vec.size(); k++) {
 
			System.out.println(vec.elementAt(k));
		}
	}
}

Ermittlung durch Array

Überarbeitete Version zum Ermitteln von Primzahlen mittels Array. Bei einem Testdurchlauf ließen sich aus 100 Mio. die Primzahlen in weniger als 3sek berechnen.

Aufruf in der Konsole:

java FasterPrime -Xmx128m

(-Xmx128m setzt den HeapSpace auf 128mb hoch)


Source-Code: FasterPrime.java

import java.util.Date;
 
public class FasterPrime {
   public static final int SIZE  = 100000000;
 
   public static void main(String[] args) {
       boolean[] arr;
       double t1, t2;
 
       System.out.println(new Date());
 
       int iSize = SIZE+1;
       arr = new boolean[iSize];
       t1 = System.currentTimeMillis();
 
       for(int i = 2; i < SIZE; i++) {
        	arr[i] = true;
       }
 
        	  arr[0] = false;
        	  arr[1] = false;
 
           for (int i=4; i<=SIZE; i+=2) {
               arr[i] = false;
           }
 
           for (int i=3; i*i<=SIZE; i+=2) {
               if (arr[i]) {
                   for (int j=i*i; j<=SIZE-1; j+=i) {
                   		arr[j] = false;
                   }
               }
           }
 
       t2 = System.currentTimeMillis();
 
       System.out.println("Time: " + (double)(t2-t1)/1000 + "s");
 
       int j=0;
       for(int i=0; i < SIZE; i++) {
        	if(arr[i]) {
        		j++;
        	}
       }
       System.out.println("Number of Primes: " + j);
    }
}

Siehe auch