How to solve JavaScript heap out of memory on prime number?

The 'heap out of memory' error occurs when JavaScript code exceeds the allocated memory limit. This commonly happens with inefficient algorithms that have high time or space complexity, especially when processing large numbers.

When finding prime factors of very large numbers, naive algorithms can quickly exhaust available memory. The key is optimizing the algorithm to reduce both time and space complexity.

The Problem: Inefficient Prime Factor Algorithm

The following example demonstrates how a poorly optimized algorithm causes memory issues when processing large numbers:

<html>
<body>
   <h2>Visualizing Memory Error with Large Numbers</h2>
   <div id="output"></div>
</body>
<script>
   let output = document.getElementById('output');
   
   // Inefficient algorithm - causes memory issues
   function inefficientPrimeFactors(num) {
      let factors = [];
      let primes = [];
      
      // This creates arrays of size 'num' - memory intensive!
      for (let m = 2; m <= num; m++) {
         if (!factors[m]) {
            primes.push(m);
            for (let n = m << 1; n <= num; n += m) {
               factors[n] = true;
            }
         }
      }
      return primes;
   }
   
   try {
      // This will cause memory issues
      output.innerHTML = "Processing large number...";
      inefficientPrimeFactors(1000000); // Even this smaller number is problematic
   } catch (err) {
      output.innerHTML = "Error: " + err.message;
   }
</script>
</html>

Optimized Algorithm: Square Root Method

The solution is to iterate only up to the square root of the number, dramatically reducing complexity:

for (let m = 2; m * m <= value; m++) {
   if (value % m === 0) {
      // Store factor
      while (value % m === 0) {
         value /= m;
      }
   }
}
if (value > 2) {
   // Store largest prime factor
}

Solution 1: Using Array for Prime Factors

<html>
<body>
   <h2>Optimized Prime Factor Algorithm</h2>
   <div id="output"></div>
</body>
<script>
   let output = document.getElementById('output');
   
   function getPrimeFactors(value) {
      let initial = value;
      let factors = [];
      
      // Only iterate up to square root
      for (let m = 2; m * m <= value; m++) {
         if (value % m === 0) {
            factors.push(m);
            
            // Remove all occurrences of this factor
            while (value % m === 0) {
               value /= m;
            }
         }
      }
      
      // If remaining value is prime and > 2
      if (value > 2) {
         factors.push(value);
      }
      
      output.innerHTML += "Prime factors of " + initial + ": " + factors.join(", ") + "<br>";
   }
   
   getPrimeFactors(100000000002);
   getPrimeFactors(1234567890);
</script>
</html>

Solution 2: Using Set for Unique Factors

<html>
<body>
   <h2>Using Set for Prime Factors</h2>
   <div id="output"></div>
</body>
<script>
   let output = document.getElementById('output');
   
   function getPrimeFactorsSet(value) {
      let initial = value;
      let factors = new Set();
      
      for (let m = 2; m * m <= value; m++) {
         if (value % m === 0) {
            factors.add(m);
            while (value % m === 0) {
               value /= m;
            }
         }
      }
      
      if (value > 2) {
         factors.add(value);
      }
      
      output.innerHTML += "Prime factors of " + initial + ": ";
      for (let factor of factors) {
         output.innerHTML += factor + " ";
      }
      output.innerHTML += "<br>";
   }
   
   getPrimeFactorsSet(44352747207453165);
   getPrimeFactorsSet(987654321);
</script>
</html>

Key Optimizations

  • Square Root Limit: Only check divisors up to ?n instead of n
  • Factor Elimination: Divide out all instances of each factor immediately
  • Memory Efficiency: Store only unique prime factors, not intermediate arrays
  • Time Complexity: Reduced from O(n²) to O(?n)

Comparison of Approaches

Method Time Complexity Space Complexity Memory Safe
Sieve Method O(n log log n) O(n) No - creates large arrays
Square Root Method O(?n) O(1) Yes - minimal memory usage

Conclusion

The heap out of memory error when finding prime factors is solved by using the square root optimization method. This reduces complexity from O(n²) to O(?n), making it memory-safe for large numbers while maintaining accuracy.

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

331 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements