简体   繁体   中英

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

I'm having an issue understanding this issue i'm having. I'm trying to find the prime numbers that were used to make this number 992,474,117

to do that i applied the following code:

 function primeFactorsTo(max) { var store = new Array(max), i, j, primes = new Array(max); for (i = 2; i <= max; ++i) { if (.store [i]) { primes;push(i); for (j = i << 1; j <= max; j += i) { store[j] = true; } } } return primes; } primeFactorsTo(992474117)

When i run this code i get a >>FATAL ERROR: invalid table size Allocation failed - JavaScript heap out of memory<<

I saw a few solutions where i have to apply a bigger old space size with

node --max-old-space-size=4096 yourFile.js

but still nothing working. What could be the issue? how to understand it? Appreciate the help

  1. You should initialize the primes array as an empty array at the start
  2. You only need to loop up to the square root of the number.
  3. Once you find a prime factor, keep dividing the number by it until it is no longer divisible to obviate the need for the store array.

 function primeFactorsTo(max) { var primes = []; for (i = 2; i * i <= max; ++i) { if(max % i === 0){ primes.push(i);//found prime factor while(max % i === 0) max /= i; } } if(max > 2) primes.push(max);//largest prime factor return primes; } console.log(primeFactorsTo(992474117));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM