Bash – Get 100 palindrome numbers

bashscripting

I'm new at scripting and I have this assignment, which is to find 100 palindrome numbers with the following algorithm:

  1. Get a two-digit random number (greater than 10)
  2. Reverse the number
  3. Sum the number and its reverse
  4. If the result of the sum is a palindrome number, print it.
    Otherwise, back to step 2

For example:

  • Starting number: 75
  • Reverse is 57
  • The sum is 75+57 = 132

As 132 is not a palindrome number, back to step 2:

  • Reverse is 321
  • 132 + 321 = 363
  • 363 is a palindrome number. Print it to stdout!

And so on until it prints 100 of these numbers.


This is what I have so far:

#! /bin/bash

CONT=0
while [ $CONT -lt 100 ] 
do
    NUM= $RANDOM
    while [ $SUM -ne $SUMINV ] 
    do

        echo $NUM > file.txt
        INV= rev file.txt
        SUM= `expr[ $NUM + $INV ]`
        echo $SUM > file2.txt
        SUMINV= rev file2.txt
        NUM= $SUM
    done
    echo $NUM
    CONT=`expr $CONT + 1`
done

Looking for solutions and help with this script!

Best Answer

As I understand firstly you need to receive two-digit number which

  • greater 10 and less 100
  • not divided by 10 (no 20;30; etc)
  • isn't palindrom (no 22;33; etc)

So you can reach it by

while :
do
  a=$[$RANDOM%10]
  b=$[$RANDOM%10]
  if [ $a -ne $b -a $a -ne 0 -a $b -ne 0 ]
  then
    NUM="$a$b"
    RNUM="$b$a"
    break
  fi
done

Next step to check the sum of number and its revers

while :
do
  NUM=$[$NUM+$RNUM]
  RNUM=$(printf "%d" $NUM | rev)
  if [ $NUM -eq $RNUM ]
  then
    echo $NUM
    break
  fi
done
Related Question