Sum of all prime numbers in JavaScript

In JavaScript, calculating the sum of all prime numbers up to a given limit is a common programming challenge. This involves identifying prime numbers and adding them together efficiently.

Understanding Prime Numbers

A prime number is a positive integer greater than 1 that has no positive divisors other than 1 and itself. For example, if we want to find the sum of all prime numbers up to 10, we identify: 2, 3, 5, 7. Their sum is 2 + 3 + 5 + 7 = 17.

Algorithm Approach

We'll implement two functions: one to check if a number is prime, and another to calculate the sum of all primes up to a given limit.

Step-by-Step Process

  1. Create a function to check if a number is prime
  2. Check divisibility from 2 to the square root of the number
  3. Create a function to sum all primes up to a limit
  4. Iterate through numbers and add primes to the total

Implementation

// Function to check if a number is prime
function isPrime(num) {
   if (num <= 1) {  // 1 and negative numbers are not prime
      return false;
   }
   
   // Check for divisors from 2 to square root of the number
   for (let i = 2; i <= Math.sqrt(num); i++) {
      // If a divisor is found, the number is not prime
      if (num % i === 0) {
         return false;
      }
   }
   
   // If no divisors are found, the number is prime
   return true;
}

// Function to calculate the sum of all prime numbers up to a limit
function sumOfPrimes(limit) {
   let sum = 0;

   for (let i = 2; i <= limit; i++) {
      // Check if the current number is prime
      if (isPrime(i)) {
         // Add the prime number to the sum
         sum += i;
      }
   }

   return sum;  // Return the final sum
}

// Example usage
const limit = 50;
const sum = sumOfPrimes(limit);
console.log("Sum of prime numbers up to", limit, "is", sum);

// Test with different limits
console.log("Sum up to 10:", sumOfPrimes(10));
console.log("Sum up to 20:", sumOfPrimes(20));
Sum of prime numbers up to 50 is 328
Sum up to 10: 17
Sum up to 20: 77

How It Works

The isPrime() function efficiently checks primality by testing divisors only up to the square root of the number. This optimization reduces the number of checks needed. The sumOfPrimes() function iterates through all numbers from 2 to the limit, calling isPrime() for each number and adding prime numbers to the running total.

Optimized Version

For better performance with larger limits, we can use the Sieve of Eratosthenes algorithm:

function sumOfPrimesOptimized(limit) {
   if (limit < 2) return 0;
   
   // Create boolean array and initialize all entries as true
   let isPrime = new Array(limit + 1).fill(true);
   isPrime[0] = isPrime[1] = false;
   
   // Sieve of Eratosthenes
   for (let i = 2; i * i <= limit; i++) {
      if (isPrime[i]) {
         for (let j = i * i; j <= limit; j += i) {
            isPrime[j] = false;
         }
      }
   }
   
   // Calculate sum of all prime numbers
   let sum = 0;
   for (let i = 2; i <= limit; i++) {
      if (isPrime[i]) {
         sum += i;
      }
   }
   
   return sum;
}

// Compare performance
console.log("Optimized sum up to 100:", sumOfPrimesOptimized(100));
Optimized sum up to 100: 1060

Complexity Analysis

Method Time Complexity Space Complexity
Basic Approach O(n × ?n) O(1)
Sieve of Eratosthenes O(n log log n) O(n)

Conclusion

This solution efficiently calculates the sum of prime numbers using a straightforward approach. For larger limits, the Sieve of Eratosthenes provides better performance with O(n log log n) time complexity.

Updated on: 2026-03-15T23:19:00+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements