Python: Check Whether Two Numbers Are Factors of Each Other
In mathematics, if two numbers are factors of each other, it means they are divisible by each other, i.e., dividing one number by the other leaves no remainder. We can write a simple Python program to check whether two numbers are factors of each other.
Example
def are_mutual_factors(a, b):
if a % b == 0 and b % a == 0:
return True
else:
return False
# Test
num1 = 12
num2 = 6
result = are_mutual_factors(num1, num2)
print(f"{num1} and {num2} are factors of each other: {result}")
if a % b == 0 and b % a == 0:
return True
else:
return False
# Test
num1 = 12
num2 = 6
result = are_mutual_factors(num1, num2)
print(f"{num1} and {num2} are factors of each other: {result}")
Code explanation:
are_mutual_factors(a, b)is a function used to check whether two numbersaandbare factors of each other.a % b == 0Checkawhether it is divisible bybexactly.b % a == 0Checkbwhether it is divisible byaexactly.- If both conditions are satisfied, the function returns
True, indicating that the two numbers are factors of each other; otherwise, it returnsFalse。 - In the test section, we define two numbers
num1andnum2, and callare_mutual_factorsfunction to determine whether they are factors of each other, and finally print the result.
Output result:
12 和 6 是否互为因数: TrueOther extensions
Python3 Examples