Solved a few more problems

003: php
005: php, ruby
006: php, ruby, c
This commit is contained in:
FuryFire
2012-03-06 14:21:54 +01:00
parent 15e919438d
commit 9dd9d918bf
9 changed files with 146 additions and 0 deletions

15
ProjectEuler/003/desc.yml Normal file
View 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

View 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));
}