Created
April 30, 2015 21:11
-
-
Save masterots/72c0e24fc5088c924f5c to your computer and use it in GitHub Desktop.
Project Euler - Largest prime factor
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(n) { | |
if (isNaN(n) || !isFinite(n) || n % 1 || n < 2) { | |
return false; | |
} | |
if (n % 2== 0) { | |
return (n == 2); | |
} | |
if (n % 3== 0) { | |
return (n == 3); | |
} | |
var m = Math.sqrt(n); | |
for (var i = 5; i <= m;i += 6) { | |
if (n % i== 0) { | |
return false; | |
} | |
if (n % (i + 2) == 0) { | |
return false; | |
} | |
} | |
return true; | |
} | |
function *getFactors(inputNumber) { | |
'use strict'; | |
var smallFactor = 1; | |
var largeFactor = inputNumber; | |
while (smallFactor < largeFactor) { | |
largeFactor = inputNumber / smallFactor; | |
if (largeFactor % 1 === 0) { | |
yield smallFactor; | |
} | |
smallFactor++; | |
} | |
} | |
var largestPrimeFactor = 1; | |
var seed = 600851475143; | |
for (var factor of getFactors(seed)) { | |
if (isPrime(factor) && largestPrimeFactor <= factor) { | |
largestPrimeFactor = factor; | |
} | |
} | |
console.log(largestPrimeFactor); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment