Practical Application of divmod() function in python, or how can we use divmod() other than just calculating / and %?

494 Views Asked by At

I just want to know how can we use divmod() function for some practical application other than just calculating / and %. I want to know if yes, then how can we use divmod function to prove if a number is prime or not. This would be a perfect practical application of divmod()

2

There are 2 best solutions below

0
On

One application (don't know whether it is "practical" enough) is to determine the digits comprising an integer:

n = 12345
while n:
    n, r = divmod(n, 10)
    print(r)

Output:

5
4
3
2
1

Here the quotient is assigned back to n effectively stripping off the last digit which is available in the remainder, r.

0
On

Well, you can use it for example for changing the base of the number. For example, for base 5:

>>> x = 3456
>>> res = ""
>>> while x != 0:
...   x, m = divmod(x, 5)
...   res = str(m) + res
...
>>> print(res)
102311
>>> int(res, 5)
3456