C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Elements: The first element is the result of the integral division. And the second is the modulo result.
Usually: You can compute these numbers with the "/" and "%" operators. This sometimes does not apply for floating-point numbers.
Python program that uses divmod
a = 12
b = 7
# Call divmod.
x = divmod(a, b)
# The first part.
print(x[0])
# The second part (remainder).
print(x[1])
Output
1
5
Tip: This approach cannot make change in all combinations. A recursive method is able to generate all possibilities.
RecursionResult: The program discovers that 81 cents can be made with five coins together. This logic applies to any currency.
Python program that makes change with divmod
def make_change(cents):
# Use modulo 25 to find quarter count.
parts = divmod(cents, 25)
quarters = parts[0]
# Use modulo 5 on remainder to find nickel count.
cents_remaining = parts[1]
parts = divmod(cents_remaining, 5)
nickels = parts[0]
# Pennies are the remainder.
cents_remaining = parts[1]
# Display the results.
print("Argument:", cents)
print("Quarters:", quarters)
print("Nickels:", nickels)
print("Pennies:", cents_remaining)
# Test with 81 cents.
make_change(81)
Output
('Argument:', 81)
('Quarters:', 3)
('Nickels:', 1)
('Pennies:', 1)
Tip: Modulo is a good choice when an actual division is not needed. Otherwise, use divmod.
Python program that uses modulo
# Input values.
a = 12
b = 7
# Use modulo operator.
c = a % b
print(c)
Output
5
Here: We display whether each index in the for-loop is evenly divisible by 2, 3 and 4.
Python program that uses modulo division in loop
# Loop over values from 0 through 9.
for i in range(0, 10):
# Buildup string showing evenly divisible numbers.
line = str(i) + ":"
if (i % 4) == 0:
line += " %4"
if (i % 3) == 0:
line += " %3"
if (i % 2) == 0:
line += " %2"
# Display results for this line.
print(line)
Output
0: %4 %3 %2
1:
2: %2
3: %3
4: %4 %2
5:
6: %3 %2
7:
8: %4 %2
9: %3
Warning: We cannot define odd() by testing for a remainder of 1. This will fail on negative numbers, which are validly odd numbers.
Python program that tests for even, odd numbers
def even(number):
# Even numbers have no remainder when divided by 2.
return (number % 2) == 0
def odd(number):
# Odd numbers have 1 or -1 remainder when divided by 2.
return (number % 2) != 0
# Test even and odd methods.
print("#", "Even?", "Odd?")
for value in range(-3, 3):
print(value, even(value), odd(value))
Output
('#', 'Even?', 'Odd?')
(-3, False, True)
(-2, True, False)
(-1, False, True)
(0, True, False)
(1, False, True)
(2, True, False)