<?php
/**
* Project Euler Problem 3: Largest prime factor
*
* The prime factors of 13195 are 5, 7, 13 and 29.
*
* What is the largest prime factor of the number 600851475143 ?
*
* Problem: https://p...content-available-to-author-only...r.net/problem=3
* Solution: https://g...content-available-to-author-only...b.com/potherca-blog/ProjectEuler/blob/master/src/PHP/Solutions/Problem003.php
* Live code: https://i...content-available-to-author-only...e.com/O2tMUJ
*/
namespace Potherca\ProjectEuler\Solutions\Problem003
{
use Potherca\ProjectEuler\Calculators\PrimeFactorCalculator as Calculator;
$number = 600851475143;
$solution = (new Calculator())->getLargestPrimeFactor($number);
echo $solution;
}
namespace Potherca\ProjectEuler\Calculators
{
class PrimeFactorCalculator
{
final
public function getPrimeFactors
(int
$subject): array {
$factors = [];
$currentPrime = 2;
while ($currentPrime < $limit) {
if ($subject % $currentPrime === 0) {
$factors[] = $currentPrime;
}
}
return $factors;
}
final public function getLargestPrimeFactor(int $subject): int
{
return end($this->getPrimeFactors($subject)); }
}
}
PD9waHAKCi8qKgogKiBQcm9qZWN0IEV1bGVyIFByb2JsZW0gMzogTGFyZ2VzdCBwcmltZSBmYWN0b3IKICogCiAqIFRoZSBwcmltZSBmYWN0b3JzIG9mIDEzMTk1IGFyZSA1LCA3LCAxMyBhbmQgMjkuCiAqIAogKiBXaGF0IGlzIHRoZSBsYXJnZXN0IHByaW1lIGZhY3RvciBvZiB0aGUgbnVtYmVyIDYwMDg1MTQ3NTE0MyA/CiAqIAogKiBQcm9ibGVtOiBodHRwczovL3AuLi5jb250ZW50LWF2YWlsYWJsZS10by1hdXRob3Itb25seS4uLnIubmV0L3Byb2JsZW09MwogKiBTb2x1dGlvbjogaHR0cHM6Ly9nLi4uY29udGVudC1hdmFpbGFibGUtdG8tYXV0aG9yLW9ubHkuLi5iLmNvbS9wb3RoZXJjYS1ibG9nL1Byb2plY3RFdWxlci9ibG9iL21hc3Rlci9zcmMvUEhQL1NvbHV0aW9ucy9Qcm9ibGVtMDAzLnBocAogKiBMaXZlIGNvZGU6IG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gICAgICAgICB9CgogICAgICAgICAgICByZXR1cm4gJGZhY3RvcnM7CiAgICAgICAgfQogICAgICAgIAogICAgICAgIGZpbmFsIHB1YmxpYyBmdW5jdGlvbiBnZXRMYXJnZXN0UHJpbWVGYWN0b3IoaW50ICRzdWJqZWN0KTogaW50CiAgICAgICAgewogICAgICAgIAlyZXR1cm4gZW5kKCR0aGlzLT5nZXRQcmltZUZhY3RvcnMoJHN1YmplY3QpKTsKICAgICAgICB9CiAgICB9Cn0K