Back

Explore Courses Blog Tutorials Interview Questions

Explore Tech Questions and Answers

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

0 votes
2 views
by (1.5k points)
I was trying whether I can print a number is prime or not in Javascript and I am unable to do that. Can someone please help me?

1 Answer

0 votes
by (1.4k points)

Just follow the piece of code provided below to check if the number is prime or not. 

Code: 

// Example program to check if a number is prime or not  

const isPrime = n => { 

  if (n === 2 || n === 3return true; 

  if (n < 2 || n % 2 === 0return false; 

  return isPrimeRecursive(n); 

} 

// Iterating only over odd divisors( makes no sense to iterate over even numbers). 

const isPrimeRecursive = (ni = 3, limit = Math.floor(Math.sqrt(n))) => {   

  if (n % i === 0return false; 

  if (i >= limit) return true; // Heureka, we have a prime here! 

  return isPrimeRecursive(ni += 2, limit); 

} 

for (i = 0i <= 50i++) { 

  console.log(`${iis ${isPrime(i) ? `a` : `not a` } prime`); 

} 

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...