首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

面试题-求质数

2012-10-27 
面试题--求质数求100以内的质数(指在一个大于1的自然数中,除了1和此整数自身外,没法被其他自然数整除的数。

面试题--求质数
求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;  
    }

希望能帮助到即将去面试的童鞋们~~

热点排行