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 Necho'N('.$counter.') = '.$n;// while the number isn't palindromicwhile($n<>strrev($n)){// add one to the counter$counter++;// output the sequence number, current N and the reversed Necho'<br/>N('.$counter.') = '.$n.' + '.strrev($n).' = ';// add the reversed version to N$n+=strrev($n);// output the new valueecho$n;}?>