用java程序编程2到100之间所有素数之和,急啊,在线等答案

来源:百度知道 编辑:UC知道 时间:2024/05/15 05:15:09

修改一下
public class PrimeNumber
{
public static void main (String arg[])
{
int sum = 2;
for (int i = 3; i < 100; i +=2) {
if (isprime(i))
sum += i;
}
}
public static boolean isprime(int n){
for (int i = 3; i < n; i++) {
if ((n%i)==0) return false;
}
return true;
}
}

用筛法:
package foo;

public class TFoo {
public TFoo() {
System.out.println("TFoo Created!");
}

public static void main(String[] args) {
TFoo tfoo = new TFoo();
int i,j,sum;
int a[]=new int[101];
sum = 0;
for (i = 1; i <= 100; i++) //先元素初值设为对应的序号值
a[i] = i;
a[1] = 0; //1不是素数,先排除
for (i = 1; i <= 100; i++) {
if (a[i] == 0)
continue; //已标记为0的表示不是素数,可以排除作为被除数
for (j = i + 1; j <= 100; j++)
if (a[j] == 0)
continue;