farei cosi':
Non l'ho provato ma dovrebbe andare.Codice PHP:
public class NthPrime {
static int DEF_MAX_ARRAY_SIZE = 100; //Magari userei una struttura dati con dimensione
//variabile, tipo ArrayList
static int DEF_MAX_VALUE = 50;
public static void main (String[] args) {
int[] arrayOfPrimes = new int [arraySize];
int index = 0;
boolean isPrime;
for (int i = 1; i < DEF_MAX_VALUE; i ++) {
//Now i is the nth value we are testing for primality
isPrime = true;
for (int divisor = 2; divisor <= Math.sqrt (i); divisor ++) {
if (i % divisor == 0) {
//we found a divisor: i is not prime
isPrime = false;
break;
}
}
if (isPrime) {
arrayOfPrimes[index++] = i;
}
}
}
}
Nota il for che controlla il divisore, va fino a radice di i. Infatti se i non e' primo sicuramente uno dei suoi divisori sara' minore della sua radice quadrata.

Rispondi quotando