Created
April 12, 2018 09:22
-
-
Save gbhasha/6e3b9ac0e0487d5bf426eb8a0b1033a2 to your computer and use it in GitHub Desktop.
Print the Smallest Prime number which is in the even position of the given array.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// const inputArr = [4,1,3,14,15,18,39,56,89,101,150,165,187] // output 3 | |
// const inputArr = [9,31,38,5,62,44,38,17,19,38,50,74] // output 5 | |
const inputArr = [5,6,8,9,11,14,16,18,20,25] //output 'null' | |
const smallestPrime = (numArray) => { | |
const inputArr = numArray.slice(); | |
const isPrime = num => { | |
for(let i = 2, s = Math.sqrt(num); i <= s; i++) | |
if(num % i === 0) return false; | |
return num !== 1; | |
} | |
const isIndexEvenPosition = num => (inputArr.indexOf(num) + 1) % 2 !== 0 | |
const primeNumArray = numArray.filter(isPrime) | |
let smallestNumPosition = 0 // copy input array | |
let smallestNum = primeNumArray.sort((a,b) => a-b)[smallestNumPosition] | |
while (isIndexEvenPosition(smallestNum)) { | |
smallestNumPosition++; | |
smallestNum = primeNumArray[smallestNumPosition] | |
} | |
return smallestNum > 0 ? smallestNum : 'NULL' | |
} | |
console.log(smallestPrime(inputArr)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment