Last active
March 24, 2020 01:39
-
-
Save Dobby233Liu/fbde9fd17a141f9e190bec88735555dc to your computer and use it in GitHub Desktop.
sort numbers to a category for them
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
function isPrime(num) // https://blog.csdn.net/huang_miao_xin/article/details/51331710 | |
{ | |
if(num == 2 || num == 3) return true; | |
if(num % 6 != 1 && num % 6 != 5) return false; // 不在6的倍数两侧的一定不是质数 | |
var tmp = Math.sqrt(num); | |
for(var i = 5; i <= tmp; i += 6) if(num % i == 0 || num % (i + 2) == 0) return false; // 在6的倍数两侧的也可能不是质数 | |
return true; // 排除所有,剩余的是质数 | |
} | |
function sortNumbers(data = [27, 37, 41, 58, 61, 73, 83, 95, 11, 14, 33, 47, 57, 62, 87, 99]){ | |
var output = {primes: [], composites: [], odds: [], evens: []}; | |
for (i2 in data){ | |
var i = data[i2]; | |
if (isNaN(i) || !Number.isInteger(Number(i))) throw Error("Invaild value in data[" + i2 + "], value: " + i); | |
i = Number(i); // prevent bugs | |
(isPrime(i) ? output.primes : output.composites).push(i); | |
(i % 2 == 0 ? output.evens : output.odds).push(i); | |
} | |
return output; | |
} | |
var exports = { isPrime: isPrime, sortNumbers: sortNumbers }; | |
if (module) { // CommonJS | |
module.exports = exports; | |
} else { // standards | |
export default exports; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment