Programa para encontrar la suma de números primos entre 1 an

Escriba un programa para encontrar la suma de todos los números primos entre 1 y n.
Ejemplos: 
 

Input : 10
Output : 17
Explanation : Primes between 1 to 10 : 2, 3, 5, 7.

Input : 11
Output : 28
Explanation : Primes between 1 to 11 : 2, 3, 5, 7, 11.

Una solución simple es recorrer todos los números del 1 al n. Para cada número, comprueba si es primo . En caso afirmativo, agréguelo al resultado.
Una solución eficiente es usar la criba de Eratóstenes para encontrar todos los números primos desde hasta n y luego hacer su suma.
 

C++

// C++ program to find sum of primes in
// range from 1 to n.
#include <bits/stdc++.h>
using namespace std;
 
// Returns sum of primes in range from
// 1 to n.
int sumOfPrimes(int n)
{
    // Array to store prime numbers
    bool prime[n + 1];
 
    // Create a boolean array "prime[0..n]"
    // and initialize all entries it as true.
    // A value in prime[i] will finally be
    // false if i is Not a prime, else true.
    memset(prime, true, n + 1);
 
    for (int p = 2; p * p <= n; 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 <= n; i += p)
                prime[i] = false;
        }
    }
 
    // Return sum of primes generated through
    // Sieve.
    int sum = 0;
    for (int i = 2; i <= n; i++)
        if (prime[i])
            sum += i;
    return sum;
}
 
// Driver code
int main()
{
    int n = 11;
    cout << sumOfPrimes(n);
    return 0;
}

Java

// Java program to find
// sum of primes in
// range from 1 to n.
import java.io.*;
import java.util.*;
 
class GFG {
     
    // Returns sum of primes
    // in range from
    // 1 to n.
    static int sumOfPrimes(int n)
    {
        // Array to store prime numbers
        boolean prime[]=new boolean[n + 1];
      
        // Create a boolean array "prime[0..n]"
        // and initialize all entries it as true.
        // A value in prime[i] will finally be
        // false if i is Not a prime, else true.
        Arrays.fill(prime, true);
      
        for (int p = 2; p * p <= n; 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 <= n; i += p)
                    prime[i] = false;
            }
        }
      
        // Return sum of primes generated through
        // Sieve.
        int sum = 0;
        for (int i = 2; i <= n; i++)
            if (prime[i])
                sum += i;
        return sum;
    }
  
   // Driver code
    public static void main(String args[])
    {
        int n = 11;
        System.out.print(sumOfPrimes(n));
    }
}
 
 
// This code is contributed
// by Nikita Tiwari.

Python3

# Python program to find sum of primes
# in range from 1 to n.
 
# Returns sum of primes in range from
# 1 to n
 
def sumOfPrimes(n):
    # list to store prime numbers
    prime = [True] * (n + 1)
     
    # Create a boolean array "prime[0..n]"
    # and initialize all entries it as true.
    # A value in prime[i] will finally be
    # false if i is Not a prime, else true.
     
    p = 2
    while p * p <= n:
        # If prime[p] is not changed, then
        # it is a prime
        if prime[p] == True:
            # Update all multiples of p
            i = p * 2
            while i <= n:
                prime[i] = False
                i += p
        p += 1   
          
    # Return sum of primes generated through
    # Sieve.
    sum = 0
    for i in range (2, n + 1):
        if(prime[i]):
            sum += i
    return sum
 
# Driver code
n = 11
print(sumOfPrimes(n))
 
# This code is contributed by Sachin Bisht

C#

// C# program to find
// sum of primes in
// range from 1 to n.
using System;
 
class GFG {
     
    // Returns sum of primes
    // in range from
    // 1 to n.
    static int sumOfPrimes(int n)
    {
         
        // Array to store prime numbers
        bool []prime=new bool[n + 1];
     
        // Create a boolean array "prime[0..n]"
        // and initialize all entries it as true.
        // A value in prime[i] will finally be
        // false if i is Not a prime, else true.
        for(int i = 0; i < n + 1; i++)
        prime[i] = true;
     
         
     
        for (int p = 2; p * p <= n; 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 <= n; i += p)
                    prime[i] = false;
            }
        }
     
        // Return sum of primes
        // generated  through Sieve.
        int sum = 0;
        for (int i = 2; i <= n; i++)
            if (prime[i])
                sum += i;
        return sum;
    }
 
    // Driver code
    public static void Main()
    {
        int n = 11;
        Console.Write(sumOfPrimes(n));
    }
}
 
// This code is contributed by nitin mittal.

PHP

<?php
// PHP program to find
// sum of primes in
// range from 1 to n.
 
// Returns sum of primes
// in range from 1 to n.
function sumOfPrimes($n)
{
    // Array to store prime
    // numbers bool prime[n + 1];
    // Create a boolean array
    // "prime[0..n]" and initialize
    // all entries it as true.
    // A value in prime[i] will
    // finally be false if i is Not
    // a prime, else true.
     
    $prime = array_fill(0, $n + 1, true);
    for ($p = 2;
         $p * $p <= $n; $p++)
    {
 
        // If prime[p] is not changed,
        // then it is a prime
        if ($prime[$p] == true)
        {
 
            // Update all multiples of p
            for ($i = $p * 2;
                 $i <= $n; $i += $p)
                $prime[$i] = false;
        }
    }
 
    // Return sum of primes
    // generated through Sieve.
    $sum = 0;
    for ($i = 2; $i <= $n; $i++)
        if ($prime[$i])
            $sum += $i;
    return $sum;
}
 
// Driver code
$n = 11;
echo sumOfPrimes($n);
     
// This code is contributed
// by ajit
?>

Javascript

<script>
    // Javascript program to find
    // sum of primes in
    // range from 1 to n.
     
    // Returns sum of primes
    // in range from
    // 1 to n.
    function sumOfPrimes(n)
    {
           
        // Array to store prime numbers
        let prime = new Array(n + 1);
       
        // Create a boolean array "prime[0..n]"
        // and initialize all entries it as true.
        // A value in prime[i] will finally be
        // false if i is Not a prime, else true.
        for(let i = 0; i < n + 1; i++)
            prime[i] = true;
       
           
       
        for (let p = 2; p * p <= n; p++)
        {
       
            // If prime[p] is not changed,
            // then it is a prime
            if (prime[p] == true)
            {
       
                // Update all multiples of p
                for (let i = p * 2; i <= n; i += p)
                    prime[i] = false;
            }
        }
       
        // Return sum of primes
        // generated  through Sieve.
        let sum = 0;
        for (let i = 2; i <= n; i++)
            if (prime[i])
                sum += i;
        return sum;
    }
     
    let n = 11;
      document.write(sumOfPrimes(n));
     
</script>

Producción: 
 

28

Este artículo es una contribución de Rohit Thapliyal . Si le gusta GeeksforGeeks y le gustaría contribuir, también puede escribir un artículo usando contribuya.geeksforgeeks.org o envíe su artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks.
Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.
 

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *