/* The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ? */
// Solution
// To find the largest prime factor of a number without using brute force,
// 1. start by finding the smallest prime factor
// 2. take the initial number and divide it by the smallest prime factor, resulting in a multiple
// 3. If the resulting multiple is not equal to 1, then the 'number' is not the largest prime number
// 4. Recursively call the function until the resulting multiple is equal to 1. The 'number' will be the largest prime factor.
function largestPrimeFactor(number) {
"use strict";
var smallestFactor = 0,
i = 1,
result = 0;
// Step #1
for (i; i <= number; i += 1) {
if (number % i === 0 && i !== 1) {
smallestFactor = i;
break;
}
}
// Step #2
result = number / smallestFactor;
if (result === 1) {
return number; // Step #4
}
// Step #3
return largestPrimeFactor(result);
}
console.log(largestPrimeFactor(13195)); // Output: 29
console.log(largestPrimeFactor(600851475143)); // Output: 6857