Reputation: 137
inspired by these posts: stackoverflow post 1, stackoverflow post 2, geeksforgeeks post
I wanted to write an algorithm in R to divide two integers, giving the integer quotient and remainder without dividing or multiplying.
However, I am struggling to translate the code to R. Here is what I got so far:
Division_alternative <- function(dividend, divisor) {
# Calculate sign of divisor
if (dividend < 0 | divisor < 0) {
sign <- -1
} else {
sign <- 1
}
# Transform to positive
dividend = abs(dividend)
divisor = abs(divisor)
# Initialize the quotient
quotient = 0
while (dividend >= divisor) {
print(sign*quotient)
dividend - divisor
quotient + 1 }
}
a = 25
b = 4
print(Division_alternative(a, b))
I am not sure what is wrong with the code thus far, that it wouldn't return anything. Anyone a clue?
Upvotes: 0
Views: 804
Reputation: 1321
Using proper assignment and making our function return something, we get:
Division_alternative <- function(dividend, divisor) {
##Handle only positive cases
stopifnot((dividend > 0 && divisor >0))
quotient = 0
while (dividend >= divisor) {
# print(sign*quotient)
dividend <- dividend - divisor
quotient <- quotient + 1 }
return(list(dividend, quotient))
}
a = 25
b = 4
print(Division_alternative(a, b))
I am only handling the positive cases since it is the easiest case. I'll let you figure the logic on how to make it work in the other 3 cases since that's a) the fun in doing those things, b) I am not a CS major and never implemented a modulus and remainder function from scratch.
Upvotes: 1