百度笔试算法题:算法题:给你一个自然数N,求[6,N]之内的所有素数中,两两之和为偶数的那些偶数。

来源:互联网 发布:淘宝网保安服装 编辑:程序博客网 时间:2024/05/16 14:01
import java.util.*;

//算法题:给你一个自然数N,求[6,N]之内的所有素数中,两两之和为偶数的那些偶数。

public class baiduTest {
//判断是否素数
public static boolean sushu(int n){
for(int i =2;i<n;i++){
if((n%i) == 0)
return false;
}
return true;
};

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入一个整型数:");
int maxnum = input.nextInt();
int[] n = new int[100];
int[] a = new int[100];
int j = 0;
int i = 0;
for(int b = 6;b < maxnum ;b++){
if(sushu(b)){ 
n[j++] = b;   //如果为素数,就放入数组n中
}
}
TreeSet ts = new TreeSet(); //因为TreeSet是不可重复的、排序的,会自动帮我们过滤掉那些重复的
while(i!=j){
for(int k =i+1;k<j;k++){
int s = n[i] + n[k]; 
if(s%2 ==0){
ts.add(s);    //判断结果是否为偶数,如果是就放入TreeSet中
}
}
i++;
}
System.out.print("偶数集合为:");//输出结果
System.out.println(ts);
}
}

1 0
原创粉丝点击