Solved a few more problems
003: php 005: php, ruby 006: php, ruby, c
This commit is contained in:
15
ProjectEuler/003/desc.yml
Normal file
15
ProjectEuler/003/desc.yml
Normal file
@ -0,0 +1,15 @@
|
||||
title: Find the largest prime factor of a composite number.
|
||||
url: http://projecteuler.net/problem=3
|
||||
|
||||
desc: |
|
||||
The prime factors of 13195 are 5, 7, 13 and 29.
|
||||
What is the largest prime factor of the number 600851475143 ?
|
||||
|
||||
solution: |
|
||||
Use factorization to find the largest prime factor
|
||||
|
||||
solutions:
|
||||
solve.php:
|
||||
desc: Basic solution
|
||||
language: php
|
||||
|
33
ProjectEuler/003/solve.php
Normal file
33
ProjectEuler/003/solve.php
Normal file
@ -0,0 +1,33 @@
|
||||
<?php
|
||||
$number = 600851475143;
|
||||
|
||||
echo max(factorize($number));
|
||||
|
||||
/**
|
||||
* Returns a sorted array of the prime factorization of $num
|
||||
* @staticvar array $aFactors
|
||||
* @param type int Number to factorize
|
||||
* @return type array Prime factors
|
||||
*/
|
||||
function factorize($num) {
|
||||
// Returns a sorted array of the prime factorization of $num
|
||||
// Caches prior results. Returns empty array for |$num|<2
|
||||
// eg. factorize(360) => [5, 3, 3, 2, 2, 2]
|
||||
static $aFactors = array();
|
||||
if (2 > $num = abs($num))
|
||||
return array(); // negatives, 1, 0
|
||||
|
||||
if ($aFactors[$key = "x$num"]) { // handles doubles
|
||||
// Been there, done that
|
||||
if (($factor = $aFactors[$key]) == $num)
|
||||
return array($num);
|
||||
return array_merge(factorize($num / $factor), array($factor));
|
||||
}
|
||||
|
||||
// Find a smallest factor
|
||||
for ($sqrt = sqrt($num), $factor = 2; $factor <= $sqrt; ++$factor)
|
||||
if (floor($num / $factor) == $num / $factor)
|
||||
return array_merge(factorize($num / $factor), array($aFactors[$key] = $factor));
|
||||
|
||||
return (array($aFactors[$key] = $num));
|
||||
}
|
Reference in New Issue
Block a user