-2

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()

  • It *exists* for calculating the quotient and remainder. Presumably it's more efficient than performing the operations independently. – Tom Karzes Nov 19 '17 at 09:51
  • I want to know a program where i can use it to calculate something or find something, other than just writing divmod and calculating it. – Chanandlerbong Nov 19 '17 at 09:54
  • @AyushSaxena Say you're wanting to convert an unsigned integer to a string. You'd want to loop until the integer is 0, performing divmod on it: assign the result of the division to the integer, print the result of the mod, as it's the digit. – hnefatl Nov 19 '17 at 09:56

2 Answers2

4

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.

mhawke
  • 84,695
  • 9
  • 117
  • 138
3

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
cha0site
  • 10,517
  • 3
  • 33
  • 51