Prime Number Questions in JavaScript

vaishnavi mehrotra
2 min readMar 7, 2021

Hello Everyone! This blog will cover Prime Numbers during The Hacking School Coding Bootcamp, Remote.

What is Prime Number?

A prime number is a natural number greater than 1, which is only divisible by 1 and itself. First few prime numbers are : 2 3 5 7 11 13 17 19 23 …..

1. Write a javascript program to check the given number is a prime number or not.

function prime(n){
var factorsCount=0;
for(var i=1; i<=n;i++){
if(n%i ===0 ){
factorsCount++;
}
}
if(factorsCount === 2){
console.log(`The Given number ${n} is a prime number`);
}else{
console.log("Not prime");
}
}
prime(3);

Output: The Given number 3 is a prime number.

2. Write a javascript program to print the count of prime numbers in the given data array.

var data=[-22,33,11,44,13,78,100,23];
var prime=0;
for
(var index=0;index<data.length;index++){
var count=0;
for
(var i=1;i<=data[index];i++){
if(data[index]%i===0 ){
count++;
}
}
if(count === 2){
prime++;
}
}
console.log("Count theprime number:",prime);

Output: Count the prime number: 3.

3. Using a try-catch method to write a javascript program to print the count of prime numbers in the given data array.

try{
var data=[10,15,27,19,2,3,5,7];
var primeCounter=0;
for
(index=0;index<data.length;index++){
var factors=0;
for
(var j=1;j<=data[index];j++){
if(data[index]%j===0){
factors++;
}
}
if(factors===2){
primeCounter++;
}
}
console.log(“Count the prime number”,primeCounter);
}
catch(err){
console.log(“something wrong” + err.message);
}

Output: Count the prime number: 5.

4. Print the prime number from range (m,n), where,m,n is a positive number, and count the prime number.

function prime(m,num){
var prime=" ";
var count=0;
for
(var k=m;k<=num;k++){
var store = 0;
for
(var j = 2; j<=k; j++){
if(k% j === 0){
store++;
}
}
if(store === 1){
prime=prime+k +" ";
count=count+1; //count the number
}
}
console.log("Prime Number:",prime);
console.log("Count the prime number:",count);
}
prime(10,20);

Output: Prime Number:11 13 17 19. Count the prime number: 4.

--

--