avkLab

Kaprekar

Aug 27th, 2024 (edited)
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.29 KB | Science | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3.  
  4. """
  5. Nom du script : Kaprekar.py
  6. Auteur : Alain Van Kerckhoven
  7. Date : 26/08/2024
  8. Version : 1.0
  9. Licence : GPL
  10.  
  11. Modifications :
  12. - 26/09/2024 : Création du script (Alain Van Kerckhoven)
  13.  
  14. Description :
  15. Recherche les attracteurs de Kaprekar pour les nombres à n chiffres.
  16.  
  17.  
  18. Remarques :
  19. - Durée exponentielle (109 s pour 5 chiffres)
  20.  
  21. Dépendances :
  22. - sys
  23. - time
  24. """
  25.  
  26. import sys
  27. import time
  28.  
  29. def kaprekar_step(number, n):
  30.     """
  31.    Performs one step of the Kaprekar process.
  32.  
  33.    Args:
  34.    - number (int): The current number to process.
  35.    - n (int): The number of digits for the current process.
  36.  
  37.    Returns:
  38.    - int: The result of subtracting the ascending version of the digits from the descending version.
  39.    """
  40.     # Convert number to string and ensure it has exactly n digits (pad with zeros if necessary)
  41.     num_str = str(number).zfill(n)
  42.    
  43.     # Create ascending and descending versions of the number
  44.     ascending = int("".join(sorted(num_str)))
  45.     descending = int("".join(sorted(num_str, reverse=True)))
  46.    
  47.     # Return the difference
  48.     return descending - ascending
  49.  
  50. def find_kaprekar_attractors(n):
  51.     """
  52.    Finds the Kaprekar attractors for n-digit numbers.
  53.  
  54.    Args:
  55.    - n (int): The number of digits to consider.
  56.  
  57.    Returns:
  58.    - dict: A dictionary where the keys are attractors and the values are lists of numbers that converge to those attractors.
  59.    """
  60.     seen_numbers = {}
  61.    
  62.     # For n = 2, handle cases where numbers might reduce to a single digit
  63.     start = 10 if n == 2 else 10**(n-1)
  64.     end = 10**n
  65.    
  66.     # Iterate over all n-digit numbers
  67.     for i in range(start, end):
  68.         current = i
  69.         # Print the number being tested, overwriting the previous number
  70.         print(f"\rTesting number: {current}", end="")
  71.         sys.stdout.flush()  # Ensure the output is immediately flushed to the console
  72.        
  73.         sequence = []
  74.         while current not in sequence:
  75.             sequence.append(current)
  76.             current = kaprekar_step(current, n)
  77.            
  78.         # Identify the attractor
  79.         attractor = current
  80.         if attractor in seen_numbers:
  81.             seen_numbers[attractor].append(i)
  82.         else:
  83.             seen_numbers[attractor] = [i]
  84.    
  85.     print()  # Ensure the final output is separated properly
  86.     return seen_numbers
  87.  
  88. def main():
  89.     """
  90.    Main function to execute the Kaprekar attractor finding process.
  91.    Asks the user for the number of digits, finds attractors, and displays the results.
  92.    """
  93.     # Prompt the user for the number of digits
  94.     n = int(input("Enter the number of digits (n): "))
  95.    
  96.     # Start the timer
  97.     start_time = time.time()
  98.    
  99.     # Find the attractors for n-digit numbers
  100.     attractors = find_kaprekar_attractors(n)
  101.    
  102.     # Stop the timer
  103.     end_time = time.time()
  104.    
  105.     # Display the results
  106.     print("\nAttractors found:")
  107.     for attractor, numbers in attractors.items():
  108.         print(f"Attractor: {attractor}, Found from {len(numbers)} numbers")
  109.    
  110.     # Calculate and display the elapsed time
  111.     elapsed_time = end_time - start_time
  112.     print(f"\nCalculation completed in {elapsed_time:.2f} seconds.")
  113.  
  114. if __name__ == "__main__":
  115.     main()
  116.  
  117.  
Tags: math
Advertisement
Add Comment
Please, Sign In to add comment