📜  给定范围内所有质数的总和

📅  最后修改于: 2021-04-23 17:35:52             🧑  作者: Mango

给定范围[l,r],任务是找到该范围内所有素数的总和。
例子:

输入:l = 1和r = 6输出:10 2+3+5=10 输入:l = 4和r = 13输出:36 5+7+11+13=36

方法1 :(幼稚方法)
循环从“ l”到“ r”并添加所有为质数的数字。
下面是上述方法的实现:

C++
// C++ Program to computer sum of prime number
// in a given range
#include 
using namespace std;
 
// Method to compute the prime number
// Time Complexity is O(sqrt(N))
bool checkPrime(int numberToCheck)
{
    if(numberToCheck == 1) {
        return false;
    }
    for (int i = 2; i*i <= numberToCheck; i++) {
        if (numberToCheck % i == 0) {
            return false;
        }
    }
    return true;
}
 
// Method to iterate the loop from l to r
// If the current number is prime, sum the value
int primeSum(int l, int r)
{
    int sum = 0;
    for (int i = r; i >= l; i--) {
 
        // Check for prime
        bool isPrime = checkPrime(i);
        if (isPrime) {
 
            // Sum the prime number
            sum = sum + i;
        }
    }
    return sum;
}
// Time Complexity is O(r x sqrt(N))
 
//Driver code
int main()
{
    int l = 4, r = 13;
 
    // Call the method with l and r
    cout << primeSum(l, r);
}


Java
// Java Program to computer sum of prime number
// in a given range
public class GFG {
 
    // Method to compute the prime number
    // Time Complexity is O(sqrt(N))
    static boolean checkPrime(int numberToCheck)
    {
        if(numberToCheck == 1) {
            return false;
        }
        for (int i = 2; i*i <= numberToCheck; i++) {
            if (numberToCheck % i == 0) {
                return false;
            }
        }
        return true;
    }
 
    // Method to iterate the loop from l to r
    // If prime number detects, sum the value
    static int primeSum(int l, int r)
    {
        int sum = 0;
        for (int i = r; i >= l; i--) {
 
            // Check for prime
            boolean isPrime = checkPrime(i);
            if (isPrime) {
 
                // Sum the prime number
                sum = sum + i;
            }
        }
        return sum;
    }
    // Time Complexity is O(r x sqrt(N))
 
    // Driver code
    public static void main(String[] args)
    {
        int l = 4, r = 13;
 
        // Call the method with l and r
        System.out.println(primeSum(l, r));
    }
}


Python 3
# Python3 Program to computer sum
# of prime number in a given range
 
# from math lib import sqrt method
from math import sqrt
 
# Function to compute the prime number
# Time Complexity is O(sqrt(N))
def checkPrime(numberToCheck) :
 
    if numberToCheck == 1 :
        return False
 
    for i in range(2, int(sqrt(numberToCheck)) + 1) :
 
        if numberToCheck % i == 0 :
            return False
 
    return True
 
# Function to iterate the loop
# from l to r. If the current
# number is prime, sum the value
def primeSum(l, r) :
 
    sum = 0
 
    for i in range(r, (l - 1), -1) :
 
        # Check for prime
        isPrime = checkPrime(i)
         
        if (isPrime) :
 
            # Sum the prime number
            sum += i
 
    return sum
 
# Time Complexity is O(r x sqrt(N))
 
# Driver code    
if __name__ == "__main__" :
 
    l, r = 4, 13
 
    # Call the function with l and r
    print(primeSum(l, r))
 
# This code is contributed
# by ANKITRAI1


C#
// C# Program to computer sum
// of prime number in a given range
using System;
 
class GFG
{
 
// Method to compute the prime
// number Time Complexity is O(sqrt(N))
static bool checkPrime(int numberToCheck)
{
    if(numberToCheck == 1)
    {
        return false;
    }
    for (int i = 2;
             i * i <= numberToCheck; i++)
    {
        if (numberToCheck % i == 0)
        {
            return false;
        }
    }
    return true;
}
 
// Method to iterate the loop from l to r
// If prime number detects, sum the value
static int primeSum(int l, int r)
{
    int sum = 0;
    for (int i = r; i >= l; i--)
    {
 
        // Check for prime
        bool isPrime = checkPrime(i);
        if (isPrime)
        {
 
            // Sum the prime number
            sum = sum + i;
        }
    }
    return sum;
}
// Time Complexity is O(r x sqrt(N))
 
// Driver code
public static void Main()
{
    int l = 4, r = 13;
 
    // Call the method with l and r
    Console.Write(primeSum(l, r));
}
}
 
// This code is contributed
// by ChitraNayal


PHP
= $l; $i--)
    {
 
        // Check for prime
        $isPrime = checkPrime($i);
        if ($isPrime)
        {
 
            // Sum the prime number
            $sum = $sum + $i;
        }
    }
    return $sum;
}
 
// Time Complexity is O(r x sqrt(N))
 
// Driver code
$l = 4; $r = 13;
 
// Call the method with l and r
echo primeSum($l, $r);
 
// This code is contributed by ajit
?>


C++
// C++ Program to computer sum of prime number
// in a given range
#include 
using namespace std;
 
// Suppose the constraint is N<=1000
const int N = 1000;
 
// Declare an array for dynamic approach
int dp[N + 1];
 
// Method to compute the array
void sieve()
{
    // Declare an extra array as arr
    int arr[N + 1];
    arr[0] = 1;
    arr[1] = 1;
 
    // Iterate the loop till sqrt(n)
    // Time Complexity is O(log(n) X sqrt(n))
    for (int i = 2; i <= sqrt(N); i++)
 
        // if ith element of arr is 0 i.e. marked as prime
        if (arr[i] == 0)
 
            // mark all of it's multiples till N as non-prime
            // by setting the locations to 1
            for (int j = i * i; j <= N; j += i)
                arr[j] = 1;
 
    long runningPrimeSum = 0;
 
    // Update the array 'dp' with the running sum
    // of prime numbers within the range [1, N]
    // Time Complexity is O(n)
    for (int i = 1; i <= N; i++)
    {
        if (arr[i] == 0)
            runningPrimeSum += i;
 
        // Here, dp[i] is the sum of all the prime numbers
        // within the range [1, i]
        dp[i] = runningPrimeSum;
    }
}
 
// Driver code
int main()
{
    int l = 4, r = 13;
   
    // Compute dp
    sieve();
    cout << dp[r] - dp[l - 1];
 
    return 0;
}
 
// This code is contributedd by divyesh072019


Java
// Java Program to computer sum of prime number
// in a given range
public class GFG {
 
    // Suppose the constraint is N<=1000
    static int N = 1000;
 
    // Declare an array for dynamic approach
    static long dp[] = new long[N + 1];
 
    // Method to compute the array
    static void sieve()
    {
        // Declare an extra array as arr
        int arr[] = new int[N + 1];
        arr[0] = 1;
        arr[1] = 1;
 
        // Iterate the loop till sqrt(n)
        // Time Complexity is O(log(n) X sqrt(n))
        for (int i = 2; i <= Math.sqrt(N); i++)
 
            // if ith element of arr is 0 i.e. marked as prime
            if (arr[i] == 0)
 
                // mark all of it's multiples till N as non-prime
                // by setting the locations to 1
                for (int j = i * i; j <= N; j += i)
                    arr[j] = 1;
 
        long runningPrimeSum = 0;
 
        // Update the array 'dp' with the running sum
        // of prime numbers within the range [1, N]
        // Time Complexity is O(n)
        for (int i = 1; i <= N; i++) {
            if (arr[i] == 0)
                runningPrimeSum += i;
 
            //Here, dp[i] is the sum of all the prime numbers
            //within the range [1, i]
            dp[i] = runningPrimeSum;
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int l = 4, r = 13;
 
        // Compute dp
        sieve();
        System.out.println(dp[r] - dp[l - 1]);
    }
}


Python 3
# Python3 Program to computer sum of prime number
# in a given range
import math # for sqrt and ceil function
 
# Suppose the constraint is N<=1000
N = 1000
 
# Declare an array for dynamic approach
dp = [0] * (N + 1)
 
# Method to compute the array
def seive():
 
    # Declare an extra array as array
    array = [0] * (N + 1)
     
    array[0] = 1
    array[1] = 1
 
    # Iterate the loop till sqrt(N)
    # Time Complexity is O(log(n) X sqrt(N))
    for i in range(2, math.ceil(math.sqrt(N) + 1)):
 
        # if ith element of arr is 0
        # i.e. marked as prime
        if array[i] == 0:
             
            # mark all of it's multiples till N as
            # non-prime by setting the locations to 1
            for j in range(i * i, N + 1, i):
                array[j] = 1
     
    runningPrimeSum = 0
 
    # Update the array 'dp' with the running sum
    # of prime numbers within the range [1, N]
    # Time Complexity is O(n)
    for i in range(1, N + 1):
        if array[i] == 0:
            runningPrimeSum += i
     
        # Here, dp[i] is the sum of all the prime numbers
        # within the range [1, i]
        dp[i] = runningPrimeSum
 
# Driver Code
l = 4
r = 13
seive()
print(dp[r] - dp[l - 1])
 
# This code is contributed by Vivek Kumar Singh


C#
// C# Program to computer sum of prime number
// in a given range
using System;
public class GFG {
 
 
    // Suppose the constraint is N<=1000
    static int N = 1000;
 
    // Declare an array for dynamic approach
    static long[] dp = new long[N + 1];
 
    // Method to compute the array
    static void sieve()
    {
        // Declare an extra array as arr
        int []arr = new int[N + 1];
        arr[0] = 1;
        arr[1] = 1;
 
        // Iterate the loop till sqrt(n)
        // Time Complexity is O(log(n) X sqrt(n))
        for (int i = 2; i <= Math.Sqrt(N); i++)
 
            // if ith element of arr is 0 i.e. marked as prime
            if (arr[i] == 0)
 
                // mark all of it's multiples till N as non-prime
                // by setting the locations to 1
                for (int j = i * i; j <= N; j += i)
                    arr[j] = 1;
 
        long runningPrimeSum = 0;
 
        // Update the array 'dp' with the running sum
        // of prime numbers within the range [1, N]
        // Time Complexity is O(n)
        for (int i = 1; i <= N; i++) {
            if (arr[i] == 0)
                runningPrimeSum += i;
 
            //Here, dp[i] is the sum of all the prime numbers
            //within the range [1, i]
            dp[i] = runningPrimeSum;
        }
    }
 
    // Driver code
    public static void Main()
    {
        int l = 4, r = 13;
 
        // Compute dp
        sieve();
        Console.WriteLine(dp[r] - dp[l - 1]);
    }
}
 
 
/*This code is contributed by 29AjayKumar*/


输出:

36

时间复杂度: O(n\sqrt{n})
空间复杂度: O(1)
方法2 :(动态编程)

  1. 声明一个数组dp和arr
  2. 将数组arr填充为0
  3. 重复循环直到sqrt(N),如果arr [i] = 0(标记为质数),然后通过将相应位置标记为1来将其所有倍数设置为非质数
  4. 用运行中的质数和更新dp数组,其中每个位置’dp [i]’保留范围为[1,i]的所有质数的和

图像表示

图像

C++

// C++ Program to computer sum of prime number
// in a given range
#include 
using namespace std;
 
// Suppose the constraint is N<=1000
const int N = 1000;
 
// Declare an array for dynamic approach
int dp[N + 1];
 
// Method to compute the array
void sieve()
{
    // Declare an extra array as arr
    int arr[N + 1];
    arr[0] = 1;
    arr[1] = 1;
 
    // Iterate the loop till sqrt(n)
    // Time Complexity is O(log(n) X sqrt(n))
    for (int i = 2; i <= sqrt(N); i++)
 
        // if ith element of arr is 0 i.e. marked as prime
        if (arr[i] == 0)
 
            // mark all of it's multiples till N as non-prime
            // by setting the locations to 1
            for (int j = i * i; j <= N; j += i)
                arr[j] = 1;
 
    long runningPrimeSum = 0;
 
    // Update the array 'dp' with the running sum
    // of prime numbers within the range [1, N]
    // Time Complexity is O(n)
    for (int i = 1; i <= N; i++)
    {
        if (arr[i] == 0)
            runningPrimeSum += i;
 
        // Here, dp[i] is the sum of all the prime numbers
        // within the range [1, i]
        dp[i] = runningPrimeSum;
    }
}
 
// Driver code
int main()
{
    int l = 4, r = 13;
   
    // Compute dp
    sieve();
    cout << dp[r] - dp[l - 1];
 
    return 0;
}
 
// This code is contributedd by divyesh072019

Java

// Java Program to computer sum of prime number
// in a given range
public class GFG {
 
    // Suppose the constraint is N<=1000
    static int N = 1000;
 
    // Declare an array for dynamic approach
    static long dp[] = new long[N + 1];
 
    // Method to compute the array
    static void sieve()
    {
        // Declare an extra array as arr
        int arr[] = new int[N + 1];
        arr[0] = 1;
        arr[1] = 1;
 
        // Iterate the loop till sqrt(n)
        // Time Complexity is O(log(n) X sqrt(n))
        for (int i = 2; i <= Math.sqrt(N); i++)
 
            // if ith element of arr is 0 i.e. marked as prime
            if (arr[i] == 0)
 
                // mark all of it's multiples till N as non-prime
                // by setting the locations to 1
                for (int j = i * i; j <= N; j += i)
                    arr[j] = 1;
 
        long runningPrimeSum = 0;
 
        // Update the array 'dp' with the running sum
        // of prime numbers within the range [1, N]
        // Time Complexity is O(n)
        for (int i = 1; i <= N; i++) {
            if (arr[i] == 0)
                runningPrimeSum += i;
 
            //Here, dp[i] is the sum of all the prime numbers
            //within the range [1, i]
            dp[i] = runningPrimeSum;
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int l = 4, r = 13;
 
        // Compute dp
        sieve();
        System.out.println(dp[r] - dp[l - 1]);
    }
}

的Python 3

# Python3 Program to computer sum of prime number
# in a given range
import math # for sqrt and ceil function
 
# Suppose the constraint is N<=1000
N = 1000
 
# Declare an array for dynamic approach
dp = [0] * (N + 1)
 
# Method to compute the array
def seive():
 
    # Declare an extra array as array
    array = [0] * (N + 1)
     
    array[0] = 1
    array[1] = 1
 
    # Iterate the loop till sqrt(N)
    # Time Complexity is O(log(n) X sqrt(N))
    for i in range(2, math.ceil(math.sqrt(N) + 1)):
 
        # if ith element of arr is 0
        # i.e. marked as prime
        if array[i] == 0:
             
            # mark all of it's multiples till N as
            # non-prime by setting the locations to 1
            for j in range(i * i, N + 1, i):
                array[j] = 1
     
    runningPrimeSum = 0
 
    # Update the array 'dp' with the running sum
    # of prime numbers within the range [1, N]
    # Time Complexity is O(n)
    for i in range(1, N + 1):
        if array[i] == 0:
            runningPrimeSum += i
     
        # Here, dp[i] is the sum of all the prime numbers
        # within the range [1, i]
        dp[i] = runningPrimeSum
 
# Driver Code
l = 4
r = 13
seive()
print(dp[r] - dp[l - 1])
 
# This code is contributed by Vivek Kumar Singh

C#

// C# Program to computer sum of prime number
// in a given range
using System;
public class GFG {
 
 
    // Suppose the constraint is N<=1000
    static int N = 1000;
 
    // Declare an array for dynamic approach
    static long[] dp = new long[N + 1];
 
    // Method to compute the array
    static void sieve()
    {
        // Declare an extra array as arr
        int []arr = new int[N + 1];
        arr[0] = 1;
        arr[1] = 1;
 
        // Iterate the loop till sqrt(n)
        // Time Complexity is O(log(n) X sqrt(n))
        for (int i = 2; i <= Math.Sqrt(N); i++)
 
            // if ith element of arr is 0 i.e. marked as prime
            if (arr[i] == 0)
 
                // mark all of it's multiples till N as non-prime
                // by setting the locations to 1
                for (int j = i * i; j <= N; j += i)
                    arr[j] = 1;
 
        long runningPrimeSum = 0;
 
        // Update the array 'dp' with the running sum
        // of prime numbers within the range [1, N]
        // Time Complexity is O(n)
        for (int i = 1; i <= N; i++) {
            if (arr[i] == 0)
                runningPrimeSum += i;
 
            //Here, dp[i] is the sum of all the prime numbers
            //within the range [1, i]
            dp[i] = runningPrimeSum;
        }
    }
 
    // Driver code
    public static void Main()
    {
        int l = 4, r = 13;
 
        // Compute dp
        sieve();
        Console.WriteLine(dp[r] - dp[l - 1]);
    }
}
 
 
/*This code is contributed by 29AjayKumar*/

输出:

36

时间复杂度: O(n)
空间复杂度: O(n)