09 May 2022

Palindromic primes and moody numbers

Palindromic primes

As this is a simple task it seems fairer to generate the primes rather than using an imported module.

So let's loop over 2 to 1000, discarding anything that's divisible by a prime we've already found, which leaves us with a new found prime.

And now we have to reverse its digits and see whether the forward and reverse versions are the same. There are various ways to reverse the digits, but a simple one-liner like

$reverse = $reverse . $1 while $j =~ m|(.)|g;

seems to do the trick quickly enough.

It's interesting that the last of the 20 primes < 1000 is 929 and then there isn't another one until 10301. So there are no 4-digit palindromic primes, and I'm sure some clever person will tell us why.

Moody numbers

1 Take a positive integer p. 
2 Set q = p
3 Compute s, the sum of the squares of the digits of q.
If s is 1 then p is happy. Stop.
If s is a previously seen value of s then p is sad. Stop.
Set  q = s and go back to step 3.

This isn't too hard to code, and the required 8 happy numbers are easily within the ambit of Perl integers.

The harder bit, though, is generating the output in the format specified by Mohammad. I got all the '=>' lining up as required, but lost the will to live before lining up the squares under the corresponding digits.



No comments:

Post a Comment