Created
May 16, 2024 19:15
-
-
Save Itsindigo/983b43f7d7d72a35ae86cba6df374c1e to your computer and use it in GitHub Desktop.
315. max prime diff
This file contains 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
let calculatedPrimes = new Set([2]) | |
function isPrime(n) { | |
let prime = true | |
if (n === 1) { | |
return false | |
} | |
if (calculatedPrimes.has(n)) { | |
return true | |
} | |
outerLoop: for (let i=2; i <= Math.floor(n / 2); i++) { | |
innerLoop: for (let j=i; j <= Math.floor(n / 2); j++) { | |
let product = i * j; | |
if (i * j === n) { | |
prime=false | |
break outerLoop | |
} | |
if (product > n) { | |
break innerLoop | |
} | |
} | |
} | |
if (prime) { | |
calculatedPrimes.add(n) | |
} | |
return prime | |
} | |
/** | |
* @param {number[]} nums | |
* @return {number} | |
*/ | |
var maximumPrimeDifference = function(nums) { | |
let iFirstPrime | |
let iLastPrime | |
for (let i=0, j=nums.length-1; iFirstPrime === undefined || iLastPrime===undefined; i++, j--) { | |
if (iFirstPrime === undefined && isPrime(nums[i])) { | |
iFirstPrime = i | |
} | |
if (iLastPrime === undefined && isPrime(nums[j])) { | |
iLastPrime = j | |
} | |
} | |
return iLastPrime - iFirstPrime | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment