怎样用Java求1~10000中的所有质数最简便的方法

如题所述

运用java8新特性stream来解决

参考以下代码

/**
 * IntStream.range(1,10001) :获取一个stream,是从1-10000的
 * filter: 取出stream每个数字进行过滤,比如选取数字300,则再构造一个stream,从2-299,依次用300取余2-299中的数,若有一个是整除,余数为0的话,这个数字就不是我们要找的质数,跳过
 * forEach:打印经过filter过滤后的stream中的每个数
 */
IntStream.range(1,10001).filter(outerInt-> !IntStream.range(2,outerInt).anyMatch(innerInt->outerInt%innerInt==0))
                        .forEach(System.out::println);

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-10-26
public class Sushu {
public static void main(String []args)
{
boolean flag;
int a=1;
System.out.print("1到10000的素数有:");
for(int i=1;i<10000;i++)
{
flag=true;
// 用1到10000的数来除以自己的平方根,
// 如果能除尽的话就不是素数
for(int j=2;j<Math.sqrt(i);j++)
{
if(i%j==0)
{
flag=false;
break;
}
}
//如果是素数的话flag=true;以下的是每行
//输出10个数
if(flag)
{
if(a%10==0)
System.out.println();
System.out.print(i+" ");
a++;
}
}
}

}
第2个回答  2013-10-26
上楼的程序有误,运行结果不正确,你可以运行看看,下面是我将他的程序修改了之后的,我经过调试的,完全正确。

for(int j=2;j<i/2;j++) //这里是我修改的,将他的程序Math.sqrt(i)修改为i/2;

你可以分别将这两个程序运行一下,他上面程序运行的结果里有好多数不是素数,你可以验证验证。
第3个回答  2013-10-26
public class Primary{
public static void main(String[] args){
int i=0;
for(i=2;i<=10000;i++){
if(getPrimary(i)==true){
System.out.print(i+" ");
}
}

}
public static boolean getPrimary(int i){
int max=i/2+1;
for(int n=2;n<max;n++){
if(i%n==0){
return false;
}
}
return true;
}
}本回答被网友采纳