In Ruby, a program that performs division without using the division operator '/'

Asked 2 years ago, Updated 2 years ago, 29 views

I'm a beginner in programming.

At Ruby,
"A storage area x stores 100 and a storage area y stores 3.Solution
for x yy without the division operator "/"  Find and store in storage z."

I can't solve the problem of the reference book...
The reference book was so messy that I got an error when I wrote the program according to the answer, and I was very confused...
I want to see the correct source code once and deepen my understanding.

I look forward to hearing from you.

ruby

2022-09-29 21:41

2 Answers

If you're telling me not to use /, all I have to do is use the alias div.

x=100
y = 3
z = x.div(y)
putz

Implement / because it's too sloppy on top.

def my_div(m,n)
  m.step(n, -n).count
end
x = 100
y = 3
z = my_div(x,y)
putz

There is a problem with this implementation.It means that it does not take into account the case where the divisor is 0 and/or the divisor is negative.If the divisor is 0, the ZeroDivisionError exception will be generated just like /.Also, in negative cases, the method of eliminating negative integers when there is a remainder is not uniquely determined unless it is divisible.Because the quotient depends on whether the remainder is always positive or the same sign as the divisor or divisor, how it is implemented depends on the programming language.This is the same sign as Ruby's behavior, or divisor.

def my_div(m,n)
  raise ZeroDivisionError if n.zero?
  return my_div (-m, -n) if n.negative?
  return-my_div (-m+n-1,n) if m.negative?
  m.step(n, -n).count
end
x = 100
y = 3
z = my_div(x,y)
putz

Negative calculations are a bit suspicious, so I'm sorry if there's a mistake.There is more than one way to implement it. You can also use +, -, *, and so on.

Now, the above method is not fast.The calculation amount is O(m/n), so if m is large, it will take a lot of time.If you apply the division method that you learn in elementary school, you should be able to process it faster, and there seems to be a method that uses bit calculation.I'm sure someone will respond to the fast implementation.


2022-09-29 21:41

x=100
y = 3

defans(count, x, y)
  if x-y >y
     an(count+1,x-y,y)
  else
     count+1
   end
end

putsans(0,x,y)


2022-09-29 21:41

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.