Re: Finding prime numbers
while (j <= n) {
numbers[j - 1] = 0;
j = j + p;
}
Doesn't stop looping
Re: Finding prime numbers
Quote:
Originally Posted by ComputerJy
while (j <= n) {
numbers[j - 1] = 0;
j = j + p;
}
Doesn't stop looping
How can i stop it from doing that and work correctly?
Re: Finding prime numbers
This is the psuedo code algorithm.
Code:
Eratosthenes(n) {
a[1] := 0
for i := 2 to n do a[i] := 1
p := 2
while p2 < n do {
j := p2
while (j < n) do {
a[j] := 0
j := j+p
}
repeat p := p+1 until a[p] = 1
}
return(a)
}
Re: Finding prime numbers
This is the algorithm as I know it:
Code:
public class Sieve {
private static int upperLimit = 1000;
private static boolean[] flags;
public Sieve() {}
public static void main(String[] args) {
initialize(args);
findPrimes();
displayPrimes();
}
private static void initialize(String[] args) {
if (args.length > 0) {
upperLimit = Integer.parseInt(args[0]);
}
flags = new boolean[upperLimit + 1];
for (int position = 0; position <= upperLimit; position++) {
flags[position] = false;
}
}
private static void findPrimes() {
for (int position = 2; position <= Math.sqrt(upperLimit); position++) {
if (!flags[position]) {
int multiple = position * 2;
while (multiple <= upperLimit) {
flags[multiple] = true;
multiple += position;
}
}
}
}
private static void displayPrimes() {
for (int position = 2; position <= upperLimit; position++) {
if (!flags[position]) {
System.out.print(position + ", ");
}
}
}
}