Adam Numbers in python

An Adam number is an integer where the square of the number and the square of its reverse are also reverses of each other. For example, 12 is an Adam number:

  • Original number: 12
  • Square of the original:
    122=14412 squared equals 144
  • Reverse of the original: 21
  • Square of the reversed number:
    212=44121 squared equals 441
  • Since 144 reversed is 441, 12 is an Adam number.

    The most straightforward way to check for an Adam number in Python is to use string slicing to reverse numbers, as shown below.
    Function to check for an Adam number
    def is_adam_number(n):
        """
        Checks if a number is an Adam number.
        
        Args:
            n (int): The integer to check.
        
        Returns:
            bool: True if the number is an Adam number, False otherwise.
        """
        # Helper function to reverse a number using string conversion
        def reverse_number(num):
            return int(str(num)[::-1])
        
        # Calculate the square of the original number
        square_n = n * n
        
        # Reverse the original number
        reverse_n = reverse_number(n)
        
        # Calculate the square of the reversed number
        square_reverse_n = reverse_n * reverse_n
        
        # Check if the square of the original is the reverse of the square of the reverse
        return square_n == reverse_number(square_reverse_n)
    
    # --- Example usage ---
    print(f"Is 12 an Adam number? {is_adam_number(12)}")
    print(f"Is 13 an Adam number? {is_adam_number(13)}")
    print(f"Is 14 an Adam number? {is_adam_number(14)}")
    How the code works
    1. is_adam_number(n) function: Takes an integer n as input.
    2. reverse_number(num) function:
      • Converts the number to a string: str(num).
      • Uses string slicing [::-1] to create a reversed version of the string.
      • Converts the reversed string back to an integer.
    3. Core logic:
      • Calculates square_n by squaring the input number n.
      • Calculates reverse_n by reversing n.
      • Calculates square_reverse_n by squaring reverse_n.
      • Compares square_n with the reversed version of square_reverse_n.
      • If they are equal, the number is an Adam number and the function returns True. Otherwise, it returns False
    1. Using string manipulation
    This is the most straightforward and "Pythonic" approach. It is often the simplest to write and read.
    Method:
    1. Convert the number to a string.
    2. Use string slicing [::-1] to reverse the string.
    3. Convert the reversed string back to an integer.

    Code example:
    python
    def is_adam_string(n):
        # Convert the original number to a string and reverse it
        rev_n = int(str(n)[::-1])
    
        # Square both the original number and the reversed number
        square_n = n * n
        square_rev_n = rev_n * rev_n
    
        # Convert the squared numbers to strings and compare their reverses
        return str(square_n) == str(square_rev_n)[::-1]
    
    # Test cases
    print(f"Is 12 an Adam number (string)? {is_adam_string(12)}")   # True
    print(f"Is 14 an Adam number (string)? {is_adam_string(14)}")   # False
  • 2. Using mathematical operations
    This method avoids converting the number to a string, which can be more memory-efficient for extremely large numbers.
    Method:
    1. Use a while loop to extract the last digit of the number using the modulo operator (% 10).
    2. Build the reversed number by multiplying a reversed_number variable by 10 and adding the extracted digit.
    3. Use integer division (// 10) to drop the last digit from the original number.
  • Code example:
    python
    def reverse_math(num):
        rev = 0
        while num > 0:
            digit = num % 10
            rev = rev * 10 + digit
            num //= 10
        return rev
    
    def is_adam_math(n):
        # Square the original number
        square_n = n * n
    
        # Reverse the original number
        rev_n = reverse_math(n)
    
        # Square the reversed number
        square_rev_n = rev_n * rev_n
    
        # Check if the square of the original is the reverse of the square of the reverse
        return square_n == reverse_math(square_rev_n)
    
    # Test cases
    print(f"Is 12 an Adam number (math)? {is_adam_math(12)}")    # True
    print(f"Is 14 an Adam number (math)? {is_adam_math(14)}")    # False
  • Using recursion
    Recursion provides an elegant way to solve the reversal part of the problem, though it is generally less efficient for very large numbers due to the overhead of function calls.

    Method:
    1. Create a recursive helper function that takes the number and an accumulator.
    2. The base case is when the number becomes 0.
    3. In each recursive step, extract the last digit and add it to the accumulator, then call the function again with the remaining digits.

      Code example:
      python
      def reverse_recursive(num, reversed_num=0):
          if num == 0:
              return reversed_num
          else:
              digit = num % 10
              reversed_num = reversed_num * 10 + digit
              return reverse_recursive(num // 10, reversed_num)
      
      def is_adam_recursive(n):
          # Square the original number
          square_n = n * n
      
          # Reverse the original number recursively
          rev_n = reverse_recursive(n)
      
          # Square the reversed number
          square_rev_n = rev_n * rev_n
      
          # Check if the square of the original is the reverse of the square of the reverse
          return square_n == reverse_recursive(square_rev_n)
      
      # Test cases
      print(f"Is 12 an Adam number (recursive)? {is_adam_recursive(12)}") # True
      print(f"Is 14 an Adam number (recursive)? {is_adam_recursive(14)}") # False
    Comparison of methods
    Method ProsCons
    String Manipulation- Very readable and concise.
    - Easy to implement.
    - Can be slightly less performant for huge numbers due to string conversions.
    - Uses more memory than the math-based approach.
    Mathematical Operations- More efficient for extremely large integers.
    - Uses minimal memory (O(1) space complexity).
    - Logic is more complex and less intuitive than the string method.
    Recursion- Provides a different, elegant solution.- Generally less efficient for large numbers due to stack size limitations and function call overhead.
  • أحدث أقدم

    نموذج الاتصال