Interview Question

Software Development Manager Interview

-

Amazon

Given two numbers n and m, divide n by m without using the division operator. Return both the integer answer as well as the remainder.

AnswerAdd Tags

Interview Answers

5 Answers

1

I first assumed that both numbers were positive and then used repeated subtraction to come up with the answer. Upon further discussion I felt that this took too long and tried to come up with some kind of faster method to accomplish this but I could not design it in the time required. Thinking about it there are some other choices: 1) Treat the numbers as binary and then use shifting and subtraction to divide. I can't really solve this easily. 2) Calculate ..., 16m, 8m, 4m, 2m, 1m, etc. and the subtract each of those from n if possible. If you can subtract it shift the answer and add a 1. Finally, compare the signs of n and m to set the signs of the answer.

Anonymous on

0

10 ^ (log10 m - log10 n)

Anonymous on

0

The two answers don't give you the remainder; you will still have to write code to get that

Anonymous on

0

Console.WriteLine("Enter a number n"); int n = Int32.Parse(Console.ReadLine()); Console.WriteLine("Enter a number m"); int m = Int32.Parse(Console.ReadLine()); int divisor = 0; int remainder = 0; int multiplier = 1; if (n < m) { Console.WriteLine("Divisor is 0"); Console.WriteLine("Remainder is {0}", m); } else { while (m * multiplier < n) { multiplier += 1; } divisor = multiplier - 1; remainder = n - m * (multiplier - 1); Console.WriteLine("Divisor is {0}", divisor); Console.WriteLine("Remainder is {0}", remainder); }

Anonymous on

0

n * m ^(-1)

Anonymous on

Add Answers or Comments

To comment on this, Sign In or Sign Up.