-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem35.php
More file actions
54 lines (48 loc) · 884 Bytes
/
Copy pathProblem35.php
File metadata and controls
54 lines (48 loc) · 884 Bytes
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
<?php
/*
* Prompt: How many circular primes are there below one million?
*
* Execute: php Problem35.php
*
* Answer: 55
*/
function sieve($limit) {
$primes = array_fill(0, $limit, true);
$primes[0] = false;
$primes[1] = false;
for ($i = 2; $i < $limit; $i++) {
if ($primes[$i]) {
for ($j = $i * $i; $j < $limit; $j += $i) {
$primes[$j] = false;
}
}
}
return $primes;
}
function digitRotations($n) {
$r = [];
while (true) {
$n = rotate($n);
if (in_array($n, $r)) {
break;
}
$r[] = (int) $n;
}
return $r;
}
function rotate($n) {
return substr($n, 1) . substr($n, 0, 1);
}
$limit = 1000000;
$primes = sieve($limit);
$c = 0;
for ($i = 0; $i < $limit; $i++) {
if ($primes[$i]) {
$r = digitRotations($i);
foreach ($r as $d)
if (!$primes[$d])
continue 2;
$c++;
}
}
echo $c . PHP_EOL;