Robson » Little Red Book » Palindromic numbers

Chapter 7 - Question 1

Given a positive integer, N, as a starting value generate the palindromic trace of N. E.g, for N = 67 we have:

N(1) = 67
N(2) = 67 + 76 = 143
N(3) = 143 + 341 = 484

Since 484 reads the same both forwards and backwards it is termed 'palindromic' and the trace terminates.

Solution 1

<?
   // generate a random positive number for N
   $n = mt_rand(1, 2000);
   // start a counter for showing the sequence of N
   $counter = 1;
   // output the original N
   echo 'N(' . $counter . ') = ' . $n;
 
   // while the number isn't palindromic
   while ($n <> strrev($n))
   {
       // add one to the counter
       $counter++;
       // output the sequence number, current N and the reversed N
       echo '<br/>N(' . $counter . ') = ' . $n . ' + ' . strrev($n) . ' = ';
       // add the reversed version to N
       $n+=strrev($n);
       // output the new value
       echo $n;
   }    
?>

Which produces:

N(1) = 21
N(2) = 21 + 12 = 33

Log

© 2004-17 robson | cc unless stated