From e25bdb3fd682fcdcaa776fbdb88a603325639675 Mon Sep 17 00:00:00 2001 From: crate Date: Fri, 21 Mar 2025 00:29:27 +0000 Subject: [PATCH] Add kaprekar.sh --- kaprekar.sh | 54 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 kaprekar.sh diff --git a/kaprekar.sh b/kaprekar.sh new file mode 100644 index 0000000..66db9d0 --- /dev/null +++ b/kaprekar.sh @@ -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 + +if [ $# -ne 1 ]; then + echo "Usage: $0 " + 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 \ No newline at end of file