World!Of
Numbers

WON plate
35 |

[ February 18, 2022 ]
Programming for palindromes
Patrick De Geest

This first Pari/gp program calculates the next higher palindrome
of a random input number > 0. Here is the function “Nextpal”.


Nextpal(k)= marque=length(digits(k))%2; \
if(marque==0, \
  n=digits(k); le=length(n); swl=n[1..le\2]; m=concat(swl,Vecrev(swl)); \
  if(fromdigits(m)<=fromdigits(n), swl=digits(fromdigits(swl)+1); \
    m=concat(swl,Vecrev(swl)); ); \
  if(length(m)>le, m=concat(m[1..le],[0]); k=fromdigits(m); marque=1); \
); \
if(marque==1, \
  n=digits(k); le=length(n); le2=le\2; m=concat(n[1..le2+1],Vecrev(n[1..le2])); \
  if(fromdigits(m)<=fromdigits(n), swl=digits(fromdigits(m[1..le2+1])+1); \
    m=concat(swl,Vecrev(swl[1..le2])); ); \
  if(length(m)>le, m=concat(m[1..le],[1]); ); \
); \
m=fromdigits(m); return(m);

Get it to run by using some examples

k=1; for(i=2, 2010, Nextpal(k); print(i," ",k); k=m; );
or

k=1234567891011; Nextpal(k); print("Next palindrome greater than ",k," is ",m);
Note that the very first palindrome namely '0' or zero isn't calculated
due to the syntax of the use of vectors. An error occurs, but that is
just a minor neglectible flaw.

If you are only interested in the palindromic primes
then insert the function 'isprime()' somewhere like this

k=2;cnt=0; for(i=1,2022, Nextpal(k); if(isprime(k), cnt+=1; print(cnt," ",k)); k=m; );


A000035 Prime Curios! Prime Puzzle
Wikipedia 35 Le Nombre 35 Numberland 35












































[ TOP OF PAGE]


( © All rights reserved )
Patrick De Geest - Belgium - Short Bio - Some Pictures
E-mail address : pdg@worldofnumbers.com