-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPrime_Factorization.php
69 lines (56 loc) · 1.54 KB
/
Prime_Factorization.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php
/**
* Prime Factorization
* compute all the prime factors of n.
* finds all pi, ei such that
* n = p1^e1 * p2^e2 * ... * pk^ek
* where p1, p2, ..., pk are distinct primes and
* e1, e2, ..., ek are positive numbers.
*
* Time Complexity: O(sqrt(n))
*/
function primeFactorization($n) {
$factors = [];
while ($n % 2 === 0) {
addPrime($factors, 2);
$n /= 2;
}
for ($i = 3; $i * $i <= $n; $i += 2) {
while ($n % $i === 0) {
addPrime($factors, $i);
$n /= $i;
}
}
if ($n > 2)
addPrime($factors, $n);
return $factors;
}
function addPrime(&$factors, $p) {
if (! isset($factors[ $p ]))
$factors[ $p ] = 1;
else
$factors[ $p ] ++;
}
// ----------------
// --- Examples ---
// ----------------
define("NL", PHP_SAPI === 'cli' ? "\n" : "<br />"); // define new line feed based on web/cli
function getMathRepresentation($primeFactorization) {
$r = '';
foreach ($primeFactorization as $p => $e) {
$r .= "$p^$e * ";
}
return substr($r, 0, - 3);
}
$n = 384;
$s = getMathRepresentation(primeFactorization($n));
printf("primeFactorization(%d) = %s" . NL, $n, $s);
$n = 36960;
$s = getMathRepresentation(primeFactorization($n));
printf("primeFactorization(%d) = %s" . NL, $n, $s);
$n = 123456789;
$s = getMathRepresentation(primeFactorization($n));
printf("primeFactorization(%d) = %s" . NL, $n, $s);
$n = 979797979797;
$s = getMathRepresentation(primeFactorization($n));
printf("primeFactorization(%d) = %s" . NL, $n, $s);