用java编写一个输出1到00以内的素数并求和的程序

2024-11-22 15:02:42
推荐回答(5个)
回答1:

public static int getPrimeSumOf(int num ){
int sum = 0;
boolean [] primes = primeNumbers(num);
StringBuilder sb = new StringBuilder();
if(primes != null){
for(int i = 1; i< primes.length; i++){
if(primes[i]){
// System.out.print(i+" + ");//输出
sb.append(i+" + ");
sum += i; //求和
}
}
System.out.println(sb.toString().substring(0, sb.toString().length()-2));
System.out.println("= "+ sum);
}

return sum;
}

public static boolean[] primeNumbers(int num){
if(num <=0){
System.out.println("范围必须大于0");
return null;
}
boolean [] primes = new boolean[num+1];
primes[1] = false; //排除1
Arrays.fill(primes, 2, num+1, true);//从2开始,假设都为素数
int n = (int) Math.sqrt(num);
for(int i = 1; i< n; i++){
if(primes[i]){//如果i是质数,那么i的倍数不是质数
for(int j = 2*i; j<=num; j+=i){
primes[j] = false;
}
}
}

return primes;
}

----------------------------------
public static void main(String[] args) {

getPrimeSumOf(100);

}

回答2:

提供个法子给你参考,不是效率最好的。
iResult 是求和结果,sResult 是输出结果,你在后边加输出语句输出即可。
for (int i = 2; i <= 100; i++) {
for (int j = 1; j <= i; j++) {
if (j != 1 && j != i && i%j == 0) {
break;
}
if (j == i) {

if (i == 2) {
sResult = sResult + i;
} else {
sResult = sResult + "," + i;
}
iResult = iResult + i;
}

}
}

回答3:

public class Prime {
static boolean isPrime(int k){
if(k==2)
return false;
if(k%2==0)
return false;
int j=(int)Math.sqrt(k);
if(j%2==0)
j--;
while(j>2&&k%j!=0)
j-=2;
return j<2;
}
public static void main(String args[]){
int sum=2;
System.out.println("2 ");
for(int k=3;k<=100;k+=2){
if(isPrime(k)){
sum=sum+k;
System.out.println(k);
}
}
System.out.println("素数的和为"+sum);
}
}
主要是判断素数,这个方法有很多。

回答4:

public class Test {

public static void main(String[] args) {

int sum = 0;

int i = 2;
while(i <= 100){

boolean isPrime = true;
for(int j = 2; j < i; j++){
if(i % j == 0){
isPrime = false;
break;
}
}

if(isPrime){
sum = sum + i;
}

i++;
}

System.out.println("Sum of prime number between 1 and 100 is: " + sum);

}

}
----------testing
Sum of prime number between 1 and 100 is: 1060

回答5:

public class BT {

public static void main(String[] args) {
int sum = 0;
System.out.print("2 + 3");
sum += 2 + 3;
for (int i = 4; i < 100; i++) {
if (isCable(i)) {
System.out.print(" + " + i);
sum += i;
}
}
System.out.print(" = " + sum);
}

public static boolean isCable(int number) {
for (int i = 2; i <= number / 2; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}