其实这个题无非就是考怎么编写1个核心函数
f(int n) 判断这个函数是否素数。
首先当今数学家还没有1个求素数的准确公式, 否则大部分都加密算法都可以轻松被破解。
当前的做法是,对于n这个数, 我们会用从2 开始的素数,去逐个去尝试去整除n求余数
如果某个素数能整除, 则这个数是合数。
当然我们不需要从2 开始的素数,一直吃尝试到n -1, 只需要尝试到 n \sqrt{n} n 就ok了。
思路我们就可以做操作了。
代码:
public class primeQuestion {
public static void main(String... args){
int n = 200;
List<Integer> primeList = new PrimeUitl().getPrimeList(n);
System.out.println(MessageFormat.format("The list of prime numbers up to {0} is {1}", n, primeList));
}
}
/**
* Algorithm problem: To Get the list of prime numbers from 1 to n
*
*/
class PrimeUitl{
public PrimeUitl(){
this.primeList.add(2);
}
private List<Integer> primeList = new ArrayList<>();
private List<Integer> outputList = new ArrayList<>();
public List<Integer> getPrimeList(int n){
if (n < 3){
throw new RuntimeException("n must large than 2");
}
this.outputList.clear();
this.outputList.add(1);
this.outputList.add(2);
for (int i=3; i <= n; i++ ){
if (isPrime(i)) {
this.outputList.add(i);
}
}
return this.outputList;
}
/**
* Use a common list of prime numbers to try to divide the integer n.
* If the integer n is divisible by a prime number in the list, then n is a composite number,
* otherwise n is a prime number, and we will add n to the common prime number list.
*
* @param n
* @return ture of false
*/
private boolean isPrime(int n){
for (Integer x: this.primeList){
if (x > (int) Math.sqrt(n)){
break;
}
/*
* If n is divisible by x, then n is not a prime number
*/
if (0 == n%x){
return false;
}
}
this.primeList.add(n);
return true;
}
}
输出:
The list of prime numbers up to 200 is [1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
179, 181, 191, 193, 197, 199]
``