package sample; import java.util.ArrayList; import java.util.Iterator; /** * 找出1-1000的素數! * * @author markGao * */ public class GetPrimeNumber { public static void main(String[] args) { int count = 1000; ArrayList<Integer> result = new ArrayList<Integer>(); GetPrimeNumber instance = new GetPrimeNumber(); // base on the object pass it's address to the sub-function // if it been changed in function all of it's references will // change instance.getPrimeNumber(count, result); Iterator<Integer> it = result.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } private void getPrimeNumber(int count, ArrayList<Integer> result) { // obviously 1 is prime number and 2 is not result.add(1); // so we start from 3 for (int index = 3; index < count; index++) { // add it to arrylist and get it's index result.add(index); int i = result.indexOf(index); // number could not be dive exactly by the number bigger than it for (int j = 2; j < index; j++) { if (index % j == 0) { // if be dive exactly remove it and break this circulate result.remove(i); break; } } } } }