Add kaprekar.sh

This commit is contained in:
crate 2025-03-21 00:29:27 +00:00
commit e25bdb3fd6

54
kaprekar.sh Normal file
View File

@ -0,0 +1,54 @@
#!/bin/bash
# Kaprekar's Routine Implementation
# For four-digit numbers, this routine always leads to 6174 (Kaprekar's constant)
# Usage: ./kaprekar.sh <four-digit-number>
if [ $# -ne 1 ]; then
echo "Usage: $0 <four-digit-number>"
exit 1
fi
if ! [[ $1 =~ ^[0-9]+$ ]]; then
echo "Error: Input must be a number"
exit 1
fi
num=$1
num=$(printf "%04d" $num)
if [[ $(echo $num | grep -o . | sort -u | wc -l) -eq 1 ]]; then
echo "Error: Number must have at least two different digits"
exit 1
fi
echo "Starting with number: $num"
iteration=0
KAPREKAR_CONSTANT=6174
while [ "$num" != "$KAPREKAR_CONSTANT" ] && [ $iteration -lt 7 ]; do
iteration=$((iteration + 1))
num=$(printf "%04d" $num)
ascending=$(echo $num | grep -o . | sort | tr -d '\n')
descending=$(echo $num | grep -o . | sort -r | tr -d '\n')
difference=$((10#$descending - 10#$ascending))
num=$(printf "%04d" $difference)
echo "Iteration $iteration: $descending - $ascending = $num"
if [ "$num" -eq 0 ]; then
echo "Error: Reached 0. Make sure the input has at least two different digits."
exit 1
fi
done
if [ "$num" = "$KAPREKAR_CONSTANT" ]; then
echo "Reached Kaprekar's constant ($KAPREKAR_CONSTANT) in $iteration iterations!"
else
echo "Failed to reach Kaprekar's constant in 7 iterations."
fi