I am a newbie in python, idk how to do the following question, please help.....
Many programming languages implement a function called divmod() (short for division and modulo), which returns both the quotient and the remainder when dividing two positive numbers using floor division.
The relationship among the 4 numbers can be described by the following formula:
=×+
Write a program to take inputs for the dividend and divisor of a division from user, and use a for loop to find the corresponding quotient and remainder without using /, *, //, %, and divmod(). In other words, you are only allowed to use the operators for addition and subtraction in your code.
Assume that you input 45 for the dividend and 7 for the divisor, print your result as following:
Input a positive integer for the dividend: 45
Input a positive integer for the divisor: 7
45 divided by 7 yields:
quotient: 6
remainder: 3
The code should work correctly if one entered another sets of value.
Here's an answer using a
while
loop.You have
dividend
cows anddivisor
cow-boys (don't be offended by the childish example: this is a wink to my elder son...). At the beginning, all cows are in the corral.And you haven't given any cow to any cow-boy.
Now, do an euclidean division: while you can give one cow to every cow-boy...
The result is:
Hope it's clear!
EDIT about the
for
loopIf you absolutely need to use a
for
, you can emulate awhile
using abreak
.We assume that
dividend
anddivisor
>= 1. Hence,quotient <= divisor
.If
break
is not allowed, then you can use a hack (I don't recommend this: thebreak
is simply hidden into the iterator):You could also use a recursive function: