Java examples for java.lang:int prime
return prime list equal or below n Please notice that element 0 is kept for 1 although 1 is not prime, this is preserved for usage in special occasions
//package com.java2s; public class Main { /**/*w w w. j av a 2s . c om*/ * return prime list equal or below n * Please notice that element 0 is kept for 1 although 1 is not prime, this is preserved for usage in special occasions * * @param n * @return */ public static int[] getAllPrimeBelowN(int n) { if (n == 1) { return new int[] { 1 }; } int[] temp = new int[n]; boolean[] flags = new boolean[n + 1]; temp[0] = 1; temp[1] = 2; int index = 2; int lastPrime = 2; while (lastPrime < n) { for (int i = 2; i * lastPrime <= n; i++) { flags[i * lastPrime] = true; } boolean found = false; for (int i = lastPrime + 1; i <= n; i++) { if (!flags[i]) { found = true; lastPrime = i; temp[index++] = lastPrime; break; } } if (!found) { break; } } int[] result = new int[index]; System.arraycopy(temp, 0, result, 0, index); return result; } }