###
Algorithms - Calculating Prime Numbers

In this blog, I will write a small sample showing how to calculate prime numbers in javascript using a technique called memoization.
Memoization is the technique where we add a property to a function so that it can remember its previously computed values. Let's take a look at the code.

## 5 comments:

what does "memoization" mean? is it different from cache in memory?

I wouldn't call it cache in memory since its just adding a property to a function. And in js since functions are objects, inherently, its an object property to save the state.

Memoization, in that sense, would just mean adding properties to objects to preserve state and in case of my example, improve the performance as well.

what is the benefit of doing this though? I also save the state to a variable in the function, and retrieve the state later

A simple variable inside the function will go out of scope after function execution is done.

It is a kind of memoization too.

But the way you evaluate a prime number is the worst way to do it.

In that case, most efficient way is loop upto the square root of the num.

var t = Math.sqrt(num);

for(var i=2; i<=t; i++)

{

....

}

and the most efficient way is to loop upto only primes of square root of num. if needs the primes of < sqrt(num).

Post a Comment