所有质数的和怎么编程序

时间:2025-01-27 08:03:54 网络游戏

计算所有质数的和可以通过多种编程语言实现。以下是几种不同编程语言的示例代码:

Python 示例

```python

def is_prime(num):

if num < 2:

return False

for i in range(2, int(num0.5) + 1):

if num % i == 0:

return False

return True

def sum_of_primes(n):

sum = 0

for i in range(2, n + 1):

if is_prime(i):

sum += i

return sum

n = int(input("请输入一个正整数: "))

print(f"1到{n}之间的所有质数之和为: {sum_of_primes(n)}")

```

C++ 示例

```cpp

include

include

using namespace std;

bool is_prime(int num) {

if (num < 2) return false;

for (int i = 2; i <= sqrt(num); i++) {

if (num % i == 0) return false;

}

return true;

}

int sum_of_primes(int n) {

int sum = 0;

for (int i = 2; i <= n; i++) {

if (is_prime(i)) {

sum += i;

}

}

return sum;

}

int main() {

int n;

cout << "请输入一个正整数: ";

cin >> n;

cout << "1到"<< n << "之间的所有质数之和为: " << sum_of_primes(n) << endl;

return 0;

}

```

Java 示例

```java

import java.util.Scanner;

public class PrimeSum {

public static boolean isPrime(int num) {

if (num < 2) return false;

for (int i = 2; i <= Math.sqrt(num); i++) {

if (num % i == 0) return false;

}

return true;

}

public static int sumOfPrimes(int n) {

int sum = 0;

for (int i = 2; i <= n; i++) {

if (isPrime(i)) {

sum += i;

}

}

return sum;

}

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("请输入一个正整数: ");

int n = scanner.nextInt();

System.out.println("1到" + n + "之间的所有质数之和为: " + sumOfPrimes(n));

}

}

```

JavaScript 示例

```javascript

function isPrime(num) {

if (num < 2) return false;

for (let i = 2; i <= Math.sqrt(num); i++) {

if (num % i === 0) return false;

}

return true;

}

function sumOfPrimes(n) {

let sum = 0;

for (let i = 2; i <= n; i++) {

if (isPrime(i)) {

sum += i;

}

}

return sum;

}

let n = parseInt(prompt("请输入一个正整数:"));

console.log("1到" + n + "之间的所有质数之和为: " + sumOfPrimes(n));

```

这些示例代码都实现了计算从1到给定整数n之间所有质数的和的功能。你可以选择任意一种编程语言进行尝试。