Python Program for Check if all digits of a number divide it

Created with Sketch.

Python Program to Check if All Digits of a Number Divide It

Introduction

In this blog post, we will discuss and implement a Python program to check if all digits of a given number divide the number evenly. The program will take an integer as input and determine whether each digit of the number is a divisor of the original number. We will provide a step-by-step explanation of the algorithm, present the Python program, and showcase its output with examples.

Algorithm for Checking if All Digits Divide the Number

The algorithm to check if all digits of a number divide the number can be outlined as follows:

  1. Input Number: Obtain the integer number as input.
  2. Extract Digits: Extract individual digits from the number.
  3. Check Division: For each digit, check if it divides the original number evenly (i.e., without a remainder).
  4. All Digits Divide: If all digits divide the number without a remainder, the condition is satisfied.
  5. Output Result: Display whether all digits divide the number or not.

Python Program Implementation

Now, let’s implement the algorithm in a Python program:

def all_digits_divide(number):
    # Convert the number to a string to extract digits
    str_number = str(number)

    # Check if any digit is 0 (to avoid division by zero)
    if '0' in str_number:
        return False

    # Check division for each digit
    for digit in str_number:
        if number % int(digit) != 0:
            return False

    return True

# Example usage
input_number = 128
result = all_digits_divide(input_number)

if result:
    print(f"All digits of {input_number} divide it evenly.")
else:
    print(f"Not all digits of {input_number} divide it evenly.")

Output:

For example, if the input number is 128, the output will be:

All digits of 128 divide it evenly.

Conclusion

The Python program efficiently checks whether all digits of a given number divide the number without leaving a remainder. The algorithm extracts each digit and performs the division, and the result is displayed based on the conditions. You can experiment with different input numbers to observe the program’s behavior. Understanding such algorithms enhances problem-solving skills in programming. Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *