자바 선별 법 으로 n 이내 의 소수 예제 구하 기 (자바 소수 구하 기)

 
  
/**
 * @author jxqlovedn
 * , :http://zh.wikipedia.org/zh-cn/
 */
public class AratosternyAlgorithm {

 public static void getPrimes(int n) {
  if(n < 2 || n > 1000000)   // 100 , JVM , ( )
   throw new IllegalArgumentException(" n !");

  int[] array = new int[n];   // , , 0; array[0] 0
  array[0] = 1;   // 0
  array[1] = 1;   // 1
  //
  for(int i = 2; i < Math.sqrt(n);i++) {   // 2
   if(array[i] == 0) {
    for(int j = i*i; j < n; j += i) {
     array[j] = 1;   //
    }
   }
  }

  // n , 10
  System.out.println(n + " : ");
  int count = 0;        //
  int rowLength = 10;   //
  for(int i = 0; i < array.length; i++) {
   if(array[i] == 0) {
    if(count % rowLength == 0 && count != 0) {
     System.out.println();
    }
    count++;

    System.out.print(i + "\t");
   }
  }
 }

 public static void main(String[] args) {
  getPrimes(99999);
 }
}

좋은 웹페이지 즐겨찾기