-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path41.php
50 lines (48 loc) · 1.07 KB
/
41.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
<!--
We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once. For example, 2143 is a 4-digit pandigital and is also prime.
What is the largest n-digit pandigital prime that exists?
-->
<?php $startTime = microtime(true);
function isPrime($input) {
$sq = sqrt($input);
for($i=2; $i <= $sq; $i++) {
if($input%$i==0) {
return false;
}
}
return true;
}
function recLoop($currentStr,$upTo)
{
for($b=$upTo; $b >= 1; $b--) {
if(strpos($currentStr,"".$b))
{
continue;
}
$currentStr .= $b;
if (strlen($currentStr)<=$upTo) {
$result = recLoop($currentStr,$upTo);
if ($result) {
return $result;
}
}
else {
$currentNum = intval(substr($currentStr, 1));
if (isPrime($currentNum)) {
return $currentNum;
}
}
$currentStr = substr($currentStr,0,-1);
}
}
for ($upTo=9; $upTo >= 1; $upTo--) {
$result = recLoop(".",$upTo);
if ($result) {
break;
}
}
$answer = $result;
$endTime = microtime(true);
echo "Answer: ",$answer,"\nTime: ",($endTime - $startTime),"\n";
// Answer: 7652413
// Time: 3.5s