Last active
December 10, 2015 18:28
-
-
Save ryasmi/4474686 to your computer and use it in GitHub Desktop.
Tests if a number is prime using JavaScript/Python. The function isPrime will return 0 if the value passed is prime and it's lowest prime divisor or 1 if it is not.
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 testDivisors(value, divisor1, divisor2) { | |
if ((value != divisor1) && (value % divisor1 === 0)) { | |
return divisor1; | |
} else if (value != divisor2 && value % divisor2 === 0) { | |
return divisor2; | |
} else { | |
return 0; | |
} | |
} | |
function isPrime(value) { | |
var count, divisor, maxN; | |
if (value > 1) { | |
divisor = testDivisors(value, 2, 3), | |
maxN = Math.round(Math.sqrt(value) / 6); | |
for (count = 1; count <= maxN && divisor === 0; count += 1) { | |
sixCount = 6 * count; | |
divisor = testDivisors(value, sixCount - 1, sixCount + 1); | |
} | |
return divisor; | |
} else { | |
return 1; | |
} | |
} |
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
import math | |
def testDivisors(value, divisor1, divisor2): | |
if value != divisor1 and value % divisor1 == 0: | |
return divisor1 | |
elif value != divisor2 and value % divisor2 == 0: | |
return divisor2 | |
else: | |
return 0 | |
def isPrime(value): | |
if value > 1: | |
divisor = testDivisors(value, 2, 3) | |
maxN = round(math.sqrt(value) / 6) | |
count = 1 | |
while (divisor == 0) and (count <= maxN): | |
sixCount = 6 * count | |
divisor = testDivisors(value, sixCount - 1, sixCount + 1) | |
count += 1 | |
return divisor | |
else: | |
return 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment