54 lines
		
	
	
		
			1.3 KiB
		
	
	
	
		
			Bash
		
	
	
	
	
	
			
		
		
	
	
			54 lines
		
	
	
		
			1.3 KiB
		
	
	
	
		
			Bash
		
	
	
	
	
	
#!/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 |