求指定整数以内所有的素数
程序员文章站
2022-07-15 10:19:00
...
import java.lang.Math; public class PrimeNumber { public static void main(String[] args) { int number = 100; PrimeNumber p = new PrimeNumber(); try { boolean[] primeNumber = p.getPrimeNumber(number); for (int i = 0; i < primeNumber.length; i++) { if(!primeNumber[i]) { System.out.println(i); } } } catch (Exception e) { e.printStackTrace(); } } public boolean[] getPrimeNumber(int number) throws Exception { if(number < 1) { throw new Exception("所求数值不符合要求"); } boolean[] container = new boolean[number+1]; container[0] = true; container[1] = true; for(int i = 2; i <= number; i++) { if(!container[i]) { //如果是2则不需要判断是否为素数 if(i == 2 || i==3 || i==5 || i==7) { for(int j = 2; j <= number/i; j++) { int hole = i*j; container[hole] = true; } } else { int sqrt = (int)Math.sqrt(i); for(int j = 2; j <= sqrt; j++) { if(i%j == 0) { container[i] = true; break; } } for(int j = 2;; j++) { if(i*j > number) { break; } container[i*j] = true; } } } } return container; } }
推荐阅读