Basic logics

Write a program to find the number is prime or not ?
Ans : A number which is divisible by 1 and by itself. And not by others is known as prime number

Hint : The idea is to run the loop from 2 to n-1. Check whether n is divisible by any number from (2 to n-1)

var n = 2;
for(var i=2;i<n;i++){
if(n%i==0){
console.log(‘divided by ‘,i)
break;
}
}

console.log(“The i is “,i);
if(n==i){
console.log(“Yes prime”)
}
else{
console.log(“Not prime”);
}

Write a program to find the prime factorial of a number
Example :
315 = 3*3*5*7

Solution :

function primeFactorial(n){
var arr = [];
while(n%2==0){
arr.push(2);
n = n/2;
}
for(var i = 3;i<Math.sqrt(n);i=i+2){
while(n%i==0){
arr.push(i);
n=n/i;
}
}
if(n>2){
arr.push(n);
}
return arr;
}
console.log(“The factorial is “,primeFactorial(27));

Find the duplicate elements in an array

function duplicate(arr){
var obj = {};
for(var i=0;i<arr.length;i++){
if(obj[arr[i]]){
obj[arr[i]] = obj[arr[i]] + 1;
}
else{
obj[arr[i]] = 1;
}
}
return obj;
}

var ob = duplicate([1,2,1,2,3,4,5,6]);
console.log(‘The object is ‘,ob);

 

Site Footer