PALPREM (Zeda) The TI-BASIC version. Requires OS 2.55MP (or 2.53MP) =============/ How it works/ ===========/ For the first 5 values, it simply checks the list {2,3,5,7,11}. If N>5, then it starts at 101 finds consecutive palindromes. For each palindrome that is prime, it decrements N until it is 0, then it is done. For incrementing to the next palindrome, it does not bother with palindromes with an even number of digits (except 11). Those are all divisible by 11 because in base R (r=radix), r+1 divides a number whose digits are: a0a1a2a3a4a5...aN iff a0-a1+a2-a3+a4... is 0 or divisible by r+1. Since we are using r=10, and palindromes have the property that a[i]=a[n-i], then for a palindrome with an even number of digits: p=a0a1a2...a2a1a0, so a0-a1+a2-...-a2+a1-a0, reorganising the terms, (a0-a0)+(a1-a1)+(a2-a2)+...=0, telling us that 11|p. As well, any even palindromes except 2 are not prime, and any palindrome ending with 5 is not prime (except 5). ============== ============== The program has two main parts: - Generating the next palindrome - Testing pimality =======================/ Generating Palindromes/ =====================/ I used a very simple method for this. For the first primes, 2,3,5,7,11, the program simply returns those immediately. If N>5, though, it works like this: Store 10 into a counter Now reverse the digits and append it to a new number (this should be 101) To increment the palindrome, simply inrcement the counter. When the counter reaches a value like 20,200, 2000,... increment the highest digit. (so they become 30,300,3000,...) When the counter reaches a value like 40,400, 4000,... increment the highest digit to 7. (so they become 70,700,7000,...) When the counter reaches a value like 80,800, 8000,... increment the highest digit. (so they become 90,900,9000,...) What is more, since these all create palindromes 30...03, 70...07, 90...09, they are all composite, so we add 1 to skip that case. ==================/ Testing Primality/ ================/ I have tried several techniques, but it seems that trial division is faster. Among the techniques tried, I used Fermat Primality testing using base 2 since the only strong prime palindromes were very large. However, this technique proved to be too slow in general (fast for prime numbers, slow for composite numbers). So instead, I settled on this technique: Test first if the number is divisible by {3,7,11} since these are fairly common factors of palindromes. Then if they pass that test, check if they are divisible by 30k+{13,17,19,23,29,31,37,41} up until sqrt(). =======/ Timing/ =====/ I kept track of the times with each version using n=42,100,290 for comparison. As you can see, there has been significant improvement: OS2.43 2.43 2.43 2.43 2.43 2.43 2.55MP n v1 v2 v3 v4 v5 v6 v7 Answer 42 44 40 30 27 23 20 14 18181 100 280 199 135 101 88 79 58 94049 290 4700 2256 1375 732 682 651 494 1958591