📌  相关文章
📜  使用Eratosthenes筛子在给定范围内的所有素数之和

📅  最后修改于: 2021-04-23 22:21:26             🧑  作者: Mango

给定范围[L,R]。任务是找到从L到R(包括两个端点)的给定范围内所有素数的总和。

例子

Input : L = 10, R = 20
Output : Sum = 60
Prime numbers between [10, 20] are:
11, 13, 17, 19
Therefore, sum = 11 + 13 + 17 + 19 = 60

Input : L = 15, R = 25
Output : Sum = 59

一个简单的解决方案是从L遍历到R,检查当前数字是否为质数。如果是,请将其添加到sum 。最后,打印总和。

一个有效的解决方案是使用Eratosthenes筛子查找所有达到给定极限的素数。然后,计算一个前缀求和数组以存储和,直到在限制之前的每个值为止。一旦有了前缀数组,我们只需要返回prefix [R] – prefix [L-1]。

注意:prefix [i]将存储从1到1的所有素数之和。 i

下面是上述方法的实现:

C++
// CPP program to find sum of primes
// in range L to R
#include 
using namespace std;
  
const int MAX = 10000;
  
// prefix[i] is going to store sum of primes
// till i (including i).
int prefix[MAX + 1];
  
// Function to build the prefix sum array
void buildPrefix()
{
    // Create a boolean array "prime[0..n]". A
    // value in prime[i] will finally be false
    // if i is Not a prime, else true.
    bool prime[MAX + 1];
    memset(prime, true, sizeof(prime));
  
    for (int p = 2; p * p <= MAX; p++) {
  
        // If prime[p] is not changed, then
        // it is a prime
        if (prime[p] == true) {
  
            // Update all multiples of p
            for (int i = p * 2; i <= MAX; i += p)
                prime[i] = false;
        }
    }
  
    // Build prefix array
    prefix[0] = prefix[1] = 0;
    for (int p = 2; p <= MAX; p++) {
        prefix[p] = prefix[p - 1];
        if (prime[p])
            prefix[p] += p;
    }
}
  
// Function to return sum of prime in range
int sumPrimeRange(int L, int R)
{
    buildPrefix();
  
    return prefix[R] - prefix[L - 1];
}
  
// Driver code
int main()
{
    int L = 10, R = 20;
  
    cout << sumPrimeRange(L, R) << endl;
  
    return 0;
}


Java
// Java program to find sum of primes
// in range L to R
  
import java.util.*;
import java.lang.*;
import java.io.*;
  
class GFG{
  
static final int MAX = 10000;
  
// prefix[i] is going to store sum of primes
// till i (including i).
static int prefix[]=new int[MAX + 1];
  
// Function to build the prefix sum array
static void buildPrefix()
{
    // Create a boolean array "prime[0..n]". A
    // value in prime[i] will finally be false
    // if i is Not a prime, else true.
    boolean prime[] = new boolean[MAX + 1];
      
    for(int i = 0; i < MAX+1; i++)
    prime[i] = true;
  
    for (int p = 2; p * p <= MAX; p++) {
  
        // If prime[p] is not changed, then
        // it is a prime
        if (prime[p] == true) {
  
            // Update all multiples of p
            for (int i = p * 2; i <= MAX; i += p)
                prime[i] = false;
        }
    }
  
    // Build prefix array
    prefix[0] = prefix[1] = 0;
    for (int p = 2; p <= MAX; p++) {
        prefix[p] = prefix[p - 1];
        if (prime[p] == true)
            prefix[p] += p;
    }
}
  
// Function to return sum of prime in range
static int sumPrimeRange(int L, int R)
{
    buildPrefix();
  
    return prefix[R] - prefix[L - 1];
}
  
// Driver code
public static void main(String args[])
{
    int L = 10, R = 20;
  
    System.out.println (sumPrimeRange(L, R));
  
}
}


Python3
# Python 3 program to find sum of primes
# in range L to R
from math import sqrt
  
MAX = 10000
  
# prefix[i] is going to store sum of primes
# till i (including i).
prefix = [0 for i in range(MAX + 1)]
  
# Function to build the prefix sum array
def buildPrefix():
      
    # Create a boolean array "prime[0..n]". A
    # value in prime[i] will finally be false
    # if i is Not a prime, else true.
    prime = [True for i in range(MAX + 1)]
  
    for p in range(2,int(sqrt(MAX)) + 1, 1):
          
        # If prime[p] is not changed, then
        # it is a prime
        if (prime[p] == True):
              
            # Update all multiples of p
            for i in range(p * 2, MAX + 1, p):
                prime[i] = False
  
    # Build prefix array
    prefix[0] = 0
    prefix[1] = 0
    for p in range(2, MAX + 1, 1):
        prefix[p] = prefix[p - 1]
        if (prime[p]):
            prefix[p] += p
  
# Function to return sum of prime in range
def sumPrimeRange(L, R):
    buildPrefix()
  
    return prefix[R] - prefix[L - 1]
  
# Driver code
if __name__ == '__main__':
    L = 10
    R = 20
    print(sumPrimeRange(L, R))
  
# This code is contributed by
# Surendra_Gangwar


C#
// C# program to find sum of 
// primes in range L to R
using System;
class GFG
{
  
static int MAX = 10000;
  
// prefix[i] is going to
// store sum of primes
// till i (including i).
static int []prefix = new int[MAX + 1];
  
// Function to build the
// prefix sum array
static void buildPrefix()
{
    // Create a boolean array "prime[0..n]".
    // A value in prime[i] will finally 
    // be false if i is Not a prime, 
    // else true.
    bool []prime = new bool[MAX + 1];
      
    for(int i = 0; i < MAX+1; i++)
    prime[i] = true;
  
    for (int p = 2; p * p <= MAX; p++) 
    {
  
        // If prime[p] is not changed, 
        // then it is a prime
        if (prime[p] == true) 
        {
  
            // Update all multiples of p
            for (int i = p * 2; i <= MAX; i += p)
                prime[i] = false;
        }
    }
  
    // Build prefix array
    prefix[0] = prefix[1] = 0;
    for (int p = 2; p <= MAX; p++) 
    {
        prefix[p] = prefix[p - 1];
        if (prime[p] == true)
            prefix[p] += p;
    }
}
  
// Function to return sum
// of prime in range
static int sumPrimeRange(int L, int R)
{
    buildPrefix();
  
    return prefix[R] - prefix[L - 1];
}
  
// Driver code
public static void Main()
{
    int L = 10, R = 20;
  
    Console.WriteLine(sumPrimeRange(L, R));
}
}
  
// This code is contributed 
// by anuj_67


输出:
60