Let’s start with an enumerated illustration. A company wants to use the minimum number of requests for an online service. They also want to complete the work in parallel mode to minimize the total time without wasting any processor in an idle state.
When they use two parallel requests they find that in the last round only one processor is busy, which means the other one is idle. They decide to use three processors and distribute the number of requests evenly…to their surprise, they again still find one processor in the last round while the other two are idle. They use four processors the next time, then five, six…again to the result that only one processor is busy in the last round, all others are wasted. They finally use seven processors and all work equally, without any wasted cycle.
So, what can we learn about the least number of requests here?
Let’s dive right in!
We’ll cover:
Learn to Code: Python for Absolute Beginners
The tools that help create a document, a movie, or a game are all programs. This course uses Python as its programming language. Python programmers are in high demand. The programs you’ll learn in this course are specially designed for learners with no programming background. You’ll start with simple math, real-world problem-solving, and writing solutions as steps in a simple language. Next, you’ll learn decision-based solutions demonstrated via flowcharts and explained with execution sheets. Finally, you’ll learn to translate your solutions into Python programs using variables, conditional statements, loops, strings, lists, and built-in functions. You’ll also learn to create your own functions in Python. Plenty of practice programs with the facility of editing and running them in an embedded way will add to your confidence. After completing this course, you can start as a Python developer. Python is used in business, web, healthcare, education, data science, scraping, embedded systems, and games.
You might have heard of the coin distribution problem, which is very similar to the one narrated in the abstract. Let’s review it briefly:
When distributing number of coins among two, three, four, five, or six people, one coin is left over. But when distributed among seven people, they are distributed equally. Similarly, in the problem of the parallel processor mentioned above, the number of requests are completely divisible by only seven; one request remains in the last round when there are two, three, four, five, or six of them.
The following conditional expressions can correctly test the value of n
:
(
(
(n % 2) == (n % 3) ==
(n % 4) == (n % 5) ==
(n % 6) == 1
)
and (n % 7) == 0
)
What does the modulo %
operator mean? This is the modulus operator that divides the left-hand side by the right-hand side and returns the remainder (not the quotient). We need to test the natural numbers until we reach the value of n
such that the above condition is true
. We can reduce iterations through the least common multiple of 2
, 3
, 4
, 5
, and 6
. Let’s stick to the topic, not the example.
One of the most common examples of modulus is the time on the clock. It keeps rounding to the smallest value whenever it crosses its largest value. For example, after 59 the minutes and seconds are rounded to 0. Similarly, the value of hours becomes 0 after 23 (for a 24-hours clock) and 1 after 12 (in a 12-hours clock). To implement the same logic for minutes and seconds in Python, we can do the following:
var = var + 1
if (var == 60): var = 0
var = var + 1
var = var % 60
Similarly, we can implement the logic for the hours part depending upon the type of clock (12-hour or 24-hour).
Modulus is a valuable operation in computer science.
Zero to Hero in Python
Python is powering the global job market and is one of the leading programming languages today because of its high scalability and ease of use. If you don't have a programming background, this Skill Path is the perfect place for you to start learning about Python. In this Skill Path, you will learn about real-world problem-solving techniques and how to write step-by-step solutions in English and Python. You will start by covering the basic syntax and functionality of Python to create basic programs. In the latter half of this Skill Path, you will get a detailed overview of object-oriented programming to create scalable, modular, and cleaner code. Moreover, you will get hands-on experience practicing with commonly used algorithms and data structures. By the end of this Skill Path, you will build a Rock, Paper, and Scissors game and its desktop app using the Tkinter library in Python to enhance your programming skills and kickstart your career as a Python developer.
Talking to new Python programmers, the following are the common uses of the modulus operator:
Whether a number is even or odd: number % 2
returns a non-zero value (True
) if number
is odd.
Check if is divisible by : N % M
returns 0
if N
is divisible by M
.
Check if is a multiple of : N % M
returns 0
if N
is a multiple by M
.
Get the last digits of a number : N % (10 ** M)
Wrapping values (for array indices): index = index % len(array)
restricts index
to remain between 0
and len(array) - 1
, both inclusive.
Forcing a number to a certain multiple: tens = value - (value % 10)
Put a cap on a particular value: hour % 24
returns a number between 0
and 23
.
Bitwise operations: x % 256
is the same value as x & 255
.
Commonly used in hashing: h(k) = k % m
maps a key k
into one of the m
buckets.
The following basic programs are examples of other common uses of the modulus operator:
Returning a fraction instead of a decimal-point result of a division:
# frac (7, 3) returns (2,1,3)
# frac (6, 3) returns (2,0,3)
# frac (6,0) returns (None,0,0)
def frac(n, d):
if d==0: return (None, 0, d)
return (n//d, n%d, d)
Converting an elapsed time (given in seconds) into hours, minutes, and seconds:
# time (5000) returns (1,23,20)
# time (500) returns (0,8,20)
# time (50) returns (0,0,50)
def time(s):
ss = s % 60
s //= 60
mm = s % 60
s //= 60
hh = s % 24
return (hh, mm, ss)
The progress is only reported every time through the loop (to do something every iteration as opposed to doing on every iteration):
# loop (70) prints 0,10,20,30,40,50,60,69
# loop (30) prints 0,10,29,29
# loop (15) prints 0,10,14
def loop(s):
for i in range(s):
if i%10 == 0:
print(i,end=',')
print(i)
Reversing the digits in a number.
# rev (1579) returns 9751
# rev (234) returns 432
# rev (60) returns 6
def rev(n):
r = 0
while n>0:
d = n % 10
r = r * 10 + d
n //= 10
return r
Converting an integer in base 10 (decimal) to another base:
# octa (255) returns 377
# octa (63) returns 77
# octa (7) returns 7
def octa(n):
b = 8
t = 1
r = 0
while n>0:
d = n % b
r = t * d + r
t = t * 10
n //= 8
return r
Converting a linear array to a matrix structure:
# a1to2 ([10,20,30,40]) returns [[10, 20], [30, 40]]
# a1to2 ([10,20,30,40,50]) returns [[10, 20], [30, 40], [50, 0]]
# a1to2 ([10,20,30,40,50,60,70,80]) returns [[10, 20], [30, 40], [50, 60], [70, 80]]
def a1to2(a1):
s = len(a1)
cols = int(s ** 0.5)
rows = s // cols
if rows*cols < s: rows = rows+1
print(rows,cols)
a2 = [[0 for i in range(cols)] for j in range(rows)]
for i in range(s):
r = i // cols
c = i % cols
a2[r][c] = a1[i]
return a2
Computing the greatest common divisor:
# gcd (12340,236) returns 4
# gcd (10,20) returns 10
# gcd (20,10) returns 10
def gcd(a,b):
if (a>b): x,y = a,b
else: x,y=b,a
while y!=0:
r = x % y
x = y
y = r
return x
Computing the least common multiple:
# lcm (20,30) returns 60
# lcm (15,20) returns 60
# lcm (30,7) returns 210
def lcm(a,b):
if (a>b): x,y = a,b
else: x,y=b,a
l = y
while l % x > 0:
l = l + y
return l
Testing if a number is prime or composite:
# is_prime (20) returns False
# is_prime (19) returns True
# is_prime (21) returns False
def is_prime(n):
if n<2: return False
r = int(n**0.5)+1
for i in range(2,r):
if n % i == 0: return False
return True;
Modular arithmetic is used in number theory, group theory, and cryptography.
Grokking Coding Interview Patterns in Python
With thousands of potential questions to account for, preparing for the coding interview can feel like an impossible challenge. Yet with a strategic approach, coding interview prep doesn’t have to take more than a few weeks. Stop drilling endless sets of practice problems, and prepare more efficiently by learning coding interview patterns. This course teaches you the underlying patterns behind common coding interview questions. By learning these essential patterns, you will be able to unpack and answer any problem the right way — just by assessing the problem statement. This approach was created by FAANG hiring managers to help you prepare for the typical rounds of interviews at major tech companies like Apple, Google, Meta, Microsoft, and Amazon. Before long, you will have the skills you need to unlock even the most challenging questions, grok the coding interview, and level up your career with confidence. This course is also available in JavaScript, Python, Go, and C++ — with more coming soon!
Mathematically, it is always guaranteed that
if
q, r = divmod(n, d)
,
then
q * d + r == n
.
The divmod()
receives a number n
and divisor d
as parameters and returns a quotient q
and a remainder r
as results. The sign of the remainder depends on the sign of the divisor:
The following table shows a comparison of positive and negative divisors in Python, along with the reasoning.
Consider | 21 % 4 is 1 | 21 % -4 is -3 |
---|---|---|
Because | 21 // 4 == 5 | 21 // -4 == -6 |
Compare | 5 * 4 + 1 == 21 | (-6) * (-4) + (-3) == 21 |
So what does the modulo ‘%’ operator do for decimal type objects? In Python, the result of the %
operator for Decimal
type objects is different from the result of the %
operator for simple integers.
The sign of the numerator is used with the result when the
Decimal
object is used as the operand. Otherwise, the sign of the denominator is used.
# Four combinations of Signs of numerator vs. denominator# for simple int values#using `%` operatorprint("(21 % 4) is", 21 % 4) # 1print("(21 % -4) is", 21 % -4) # -3print("(-21 % 4) is", -21 % 4) # 3print("(-21 % -4) is", -21 % -4) # -1print("------------------------------------------------------------")#using `divmod()` functionq, r = divmod(21, 4)print("divmod(21, 4) is", (q,r)," ===>> ",q,"*",4,"+ ",r,"=",21)q, r = divmod(21, -4)print("divmod(21, -4) is", (q,r)," ===>> ",q,"*",-4,"+",r,"=",21)q, r = divmod(-21, 4)print("divmod(-21, 4) is", (q,r)," ===>> ",q,"*",4,"+ ",r,"=",-21)q, r = divmod(-21, -4)print("divmod(-21, -4) is", (q,r)," ===>> ",q,"*",-4,"+",r,"=",-21)
In the above code, we have demonstrated the change in the remainder due to the change in the sign of the denominator. The first group of statements uses the %
operator while the other uses the divmod()
function to show the quotient for clarity of the remainder value.
# Four combinations of Signs of numerator vs. denominator# for Decimal type objectsfrom decimal import Decimalfor i in range(9):print(Decimal(i) % Decimal(4)," , ",Decimal(-i) % Decimal(4)," , ",Decimal(i) % Decimal(-4)," , ",Decimal(-i) % Decimal(-4))
In the above code, the result carries the sign of the numerator used in the expression. The remainder value results from simple (unsigned) values of operands without following the rule q * d + r == n
.
Be cautious when using the
Decimal
objects with the%
operator in Python. The result is different from that of simple integers.
The modulus operator in Python is represented with the %
operator. There are other built-in functions like divmod()
that can be used to compute the remainder as a result of division. For simple integers, Python guarantees q * d + r == n
for q, r = divmod(n, d)
. The result of the %
operator differs if the operands are the objects of the Decimal
type.
Happy learning!
To start learning these concepts and more, check out Educative’s Zero to Hero in Python skill path.
Free Resources