双素数问题的解决办法

public class GetChar {
    //按大小顺序存放1000以内的素数
    List<Integer> list = new ArrayList<Integer>();
    
    //输出差值为2的双素数
    public void getTwinPrimes(int n){
        int m = getListOfPrime(n).size();
        for(int i = 0;i < m - 1;i++){
            int x = (Integer) list.get(i);
             int y = (Integer) list.get(i+1);
             if(y - x == 2){
                 System.out.println("(" + x + ", " + y + ")");
             } 
        }
    }

    //将1000以内的所有素数全都放入到一个数组里面
    public List<Integer> getListOfPrime(int n){
        for(int i = 2;i <= n;i++){
            if(isPrime(i) == true){
                list.add(i);
            }
        }
        return list;
    }
    
    //确定1000以内的所有数是否是素数
    public boolean isPrime(int n){
        boolean flag = true;
        for(int i = 2;i < n;i++){
            if(n % i == 0){
                flag = false;
            }
        }
        return flag;
    }
    
    public static void main(String[] args) {
        GetChar gc = new GetChar();
        gc.getTwinPrimes(7);    
    }
}

 

posted @ 2017-03-20 20:44  Gsk.Space  阅读(513)  评论(0)    收藏  举报