Toy Problem Prime Tester

Zied Sradkii
2 min readFeb 11, 2021

Hello, my lovely hackers! Today, we are going to start a new experience which is An Algorithm a Day; every day, will post an algorithm and we will solve it together.
Our algorithm for today is: A prime number is a whole number that has no other divisors other than itself and 1.
1/Write a function that accepts a number and returns true if it’s a prime number, false if it’s not.
2/Write a function that generates a list of all prime numbers in a user-specified range (inclusive)

After we read the problem and understand, we are going to start :
The first thing we should know is what is a prime number, Prime numbers are numbers that have only 2 factors: 1 and themselves. For example, the first 5 prime numbers are 2, 3, 5, 7, and 11. By contrast, numbers with more than 2 factors are called composite numbers.

In this function, we are going to test if a number is prime or not:
function test_prime(n)
{

if (n===1)
{
return false;
}
else if(n === 2)
{
return true;
}else
{
for(var x = 2; x < n; x++)
{
if(n % x === 0)
{
return false;
}
}
return true;
}
}

In this function we are going to gonna generate a list of a prime numbers in a user-specified range .
var primeSieve = function(start,end){
var current =2;
var primes=range(0, end);
while(current<Math.sqrt(end)){
//mark all multiple not prime
for (var i= current*2;i<=end; i += current){
primes[i] = null;
}
// find the next current ❤
current += 1;
while (!primes[current]&&current <= end){
current+=1;}
}
return primes.slice(2).filter(function (val){
return val && val>=start;});
}
var range = function (start, end ) {
var result=[];
for (var i = start; i<=end; i++){result.push(i);}
//return the result :)
return result;
};
and this is our first algorithm see you guys in another blog

--

--