Created
September 5, 2024 04:45
-
-
Save msankhala/cf96e0dd38df0e8b9b87a52aba45628b to your computer and use it in GitHub Desktop.
The program that will show the kaprekar constant, Given a 4 digit number it will show how many steps it take to reach to kaprekar constant.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def kaprekar_constant(num): | |
steps = 0 | |
while num != 6174: | |
# Convert number to a 4-digit string, padding with zeros if necessary | |
num_str = f"{num:04d}" | |
# Sort digits in ascending and descending order | |
asc = int(''.join(sorted(num_str))) | |
desc = int(''.join(sorted(num_str, reverse=True))) | |
# Calculate the difference | |
num = desc - asc | |
steps += 1 | |
# Print each step | |
print(f"Step {steps}: {desc} - {asc} = {num}") | |
# Check if the number has become 6174 | |
if num == 6174: | |
print(f"Reached Kaprekar's constant in {steps} steps.") | |
return steps | |
# Check for 4-digit numbers with all same digits (e.g., 1111) | |
if len(set(num_str)) == 1: | |
print("This number will not reach Kaprekar's constant.") | |
return -1 | |
# Test the function | |
number = int(input("Enter a 4-digit number: ")) | |
kaprekar_constant(number) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment