## Pages

### 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.

Anonymous said...

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

Akhil Deshpande said...

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.

Anonymous said...

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

Akhil Deshpande said...

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

TNS said...

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).