Last active
October 15, 2017 01:50
-
-
Save jialinhuang00/ef8aaefea1e2ee6bbb6154e80c96ac70 to your computer and use it in GitHub Desktop.
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
// Using a function in arr.filter(return fun) to check true or false | |
function Prime(element, index, array) { | |
var start = 2; | |
while (start <= Math.sqrt(element)) { | |
if (element % start++ < 1) { | |
return false; | |
} | |
} | |
return element > 1; | |
} | |
[5, 6, 4, 55, 53, 7].filter(e => { | |
return Prime(e); | |
}); | |
// [ 5, 53, 7 ] |
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
/*----------------------------------------------------------------------------- | |
whether it's a prime | |
the references are from | |
UdemyCourse: LearningAlgorithmsInJavascriptFromScratch, | |
www.codecademy.com/en/forum_questions/51c858349c4e9dd24201011d | |
MDN Array.prototye.find() | |
-----------------------------------------------------------------------------*/ | |
function isPrime(n) { | |
var result = []; | |
for (var i = 2; i <= n; i++) { | |
var guessPrime = true; | |
for (var j = 2; j < Math.sqrt(n); j++) { | |
if (i % j === 0 && j !== i) { | |
guessPrime = false; | |
} | |
} | |
if (guessPrime) { | |
result.push(i); | |
} | |
} | |
return result; | |
} |
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
function sieveOfEratosthene(n) { | |
var originArr = [false, false]; | |
for (let i = 2; i <= n; i++) { | |
originArr.push(true); | |
} | |
for (var i = 2; i < Math.sqrt(n); i++) { | |
for (var j = 2; j * i <= n; j++) { | |
originArr[i * j] = false; | |
} | |
} | |
var arePrimes = []; | |
var a = originArr.forEach((n, i) => { | |
if (n) { | |
arePrimes.push(i); | |
} | |
}); | |
return arePrimes; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment