My logic for the for loops was this: Starting with the upper numbers of the ArrayList, find every number that is a multiple of that number and remove it from the ArrayList. Every time you find a multiple, increase the variable multiply, so the program knows what the next multiple to look for.
// program doesn't work yet.
import java.util.ArrayList;
// import java.util.ListIterator;
public class Sieve2
{
public static void main(String[] args)
{
int upperLimit = 55;
ArrayList<Integer> primes = new ArrayList<Integer>();
// fill the array
for(int i = 0; i < upperLimit; i++)
primes.add(i + 1);
for(int mult = upperLimit/2; mult > 1; mult--)
{
int remove = mult, multiply = 2;
for(int index = 1; index < primes.size(); index++)
{
if((remove * multiply) > upperLimit) break; // save some time
if((remove * multiply) == primes.get(index))
{
primes.remove(index);
multiply++;
}
}
}
// print the array
for(Integer j : primes)
System.out.print(j + " ");
}
}
And this is the output:
1 2 3 5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55

New Topic/Question
Reply


MultiQuote




|