The Prime Number algorithm question that you have heard many times in your school or college asked in many interviews including FAANG companies.
The question for an algorithm is,
In mathematics, the Prime number is the number that is divisible by 1 or the number itself.
Example 1:
Input: n=17
Output: true
Example 2:
Input: n=15
Output: false
Let's start with the algorithm,
var isPrime = function(n) {
var result=true;
for(let i=2;i<n;i++)
{
if(n%i==0)
{
result = false;
}
}
return result;
};
Here, we have defined the result as true by default then we have for loop that starts from 2 and ends at the number-1. We used to find the remainder when the remainder equaled zero which means that number is not a prime number.
I hope you understood the algorithm. If you have any doubts, please let us know in the comments.
0 Comments