# 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) = 296
N(2) = 296 + 692 = 988
N(3) = 988 + 889 = 1877
N(4) = 1877 + 7781 = 9658
N(5) = 9658 + 8569 = 18227
N(6) = 18227 + 72281 = 90508
N(7) = 90508 + 80509 = 171017
N(8) = 171017 + 710171 = 881188

## Log

• April 3, 2005 - Added solution 1.
© 2004-17 robson | cc unless stated