Bouncy Numbers PHP

Bouncy Numbers on projecteuler.net

Under 7 seconds with ASUS G53J (xampp) PHP.

How does it work?
We start at 0, and check each number for “bounciness” until we get an even 99% (brute force method).

Although the script could be shortened, I found this one to be the quickest PHP script yet.

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
$num = 0;
$count = 0;
$percentage = 0;

//$num = 21780;
//$count = 19602;

$ts = microtime(1);

while($percentage != 0.99)
{
    $incline = $decline = false;
    $str = (string)$num;
    $len = strlen($num);
   
    for($i = 0; $i < $len; $i++)
    {
        if(isset($str[$i + 1])){

            if($str[$i] > $str[$i+1])
            {
                $incline = true;
                if($decline)
                    break;
            }
            else if($str[$i] < $str[$i+1])
            {
                $decline = true;
                if($incline)
                    break;
            }
           
        }
    }
   
    if($incline && $decline)
      $count++;
   
   $num++;  
   $percentage = $count / $num;
}

echo $num.' - '.(microtime(1) - $ts);

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>