面试题--求质数
求100以内的质数(指在一个大于1的自然数中,除了1和此整数自身外,没法被其他自然数整除的数。)
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
for(int i=2;i<100;i++)
if(matches(i,list))//如果是质数存入到list中
list .add(i);
for(Integer a : list)
System.out.println(a);
}
private static boolean matches(int i,List<Integer> list) {
if(i == 2)//这里已经保证list不会为空
return true;
for(int a : list){
if(i%a == 0) //如果能被整除说明不是质数
return false;
}
return true;
}
希望能帮助到即将去面试的童鞋们~~