L
lulu
Gast
Hallo zusammen,
ich habe folgendes Problem: ich will eine Methode implementieren, die aus einer Reihe von Zahlen von 1 bis max alle Primzahlen als Array ausgibt. Nun kommt aber Schmarn raus, z.B. für Primzahlen < 30 wird das Array (29, 0, 0, 0, 0, 0, ....0) ausgegeben. Ich nehme an, ich hab irgendwo in der Schleife einen Fehler, aber keine Ahnung wo. Wer kann mir helfen?????
ich habe folgendes Problem: ich will eine Methode implementieren, die aus einer Reihe von Zahlen von 1 bis max alle Primzahlen als Array ausgibt. Nun kommt aber Schmarn raus, z.B. für Primzahlen < 30 wird das Array (29, 0, 0, 0, 0, 0, ....0) ausgegeben. Ich nehme an, ich hab irgendwo in der Schleife einen Fehler, aber keine Ahnung wo. Wer kann mir helfen?????
Java:
public static int[] eratosthenes(int max) {
if (max < 2) {
int[] onlyPrimes = new int [0];
System.out.println("This number is too small.");
return onlyPrimes;
}
//generate an array of the length max containing all non-negative integer numbers from 1 to max
boolean[] prim = new boolean[max];
//assume all numbers are primes until the opposite is proved
for(int i = 0; i < prim.length; i++) {
prim[i] = true;
}
//1 is not a prime
prim[1] = false;
//go through the array and set numbers that are not primes false
for(int p = 1 ; p < prim.length; p++) {
if (prim[p] == true) { //prime found
for (int v = (2 * p); v < prim.length; v = v + p) {
prim[v - 1] = false; //number can be divided by a prime, so it is not a prime => set false
}
}
}
//now all prime numbers are true and all not prime numbers are false
//counts the primes in the array to determine the length of the new array which contains only primes
int count = 0;
for (int i = 0; i < max; i++) {
if (prim[i] == true)
count++;
}
//generate an array which will contain only primes < max
int[] onlyPrimes = new int[count];
//fills the array onlyPrimes with primes < max
for (int i = 0; i < max; i++) { //the position of the element of prim
int j = 0; //the position of the element of onlyPrimes
if (prim[i] == true) {
onlyPrimes[j] = i;
j++; //increase j when a prime was found and added to onlyPrimes
}
}
System.out.println("Primes < " + max + " :");
}
System.out.println("prim: ");
for(int i = 0; i < prim.length;i++) {
System.out.println(prim[i]);
}
System.out.println("onlyPrimes: ");
for (int i = 0; i < onlyPrimes.length; i++)
System.out.println(onlyPrimes[i]);
return onlyPrimes; //return the array of primes
}
Zuletzt bearbeitet von einem Moderator: