-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2.php
More file actions
52 lines (43 loc) · 1.15 KB
/
2.php
File metadata and controls
52 lines (43 loc) · 1.15 KB
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
<?php
/**
* Each new term in the Fibonacci sequence is generated by adding the previous
* two terms. By starting with 1 and 2, the first 10 terms will be:
*
* 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
*
* By considering the terms in the Fibonacci sequence whose values do not exceed
* four million, find the sum of the even-valued terms.
*/
$start = microtime(true);
// Según el enunciado, considero a los dos primeros elementos como 1 y 2
function r_fibonacci($f) {
if ($f < 1) {
throw new Exception("No pibe");
} else if ($f == 1) {
return 1;
} else if ($f == 2) {
return 2;
} else {
return r_fibonacci($f - 1) + r_fibonacci($f - 2);
}
}
function fibonacci($f) {
$f++; // Incremento en uno para que el primer elemento sea 1 y el segundo sea 2
return round((pow(((1 + sqrt(5)) / 2), $f) - pow((-1 / (1 + sqrt(5)) / 2), $f)) / sqrt(5));
}
//for ($i = 1; $i <= 10; $i++) {
// echo round(fibonacci($i)) . "\n";
//}
$i = 1;
$f = 0;
$sum = 0;
$f = fibonacci($i);
while($f <= 4000000){
if ($f % 2 == 0) {
$sum += $f;
}
$i++;
$f = fibonacci($i);
}
echo $sum . "\n";
printf("Resultado obtenido en %.4f segundos\n", microtime(true) - $start);