Amazon Interview Question

Write a function that divides one number by another, without using the division operator, and make it better than O(n).

Interview Answers

Anonymous

Feb 11, 2015

Use logarithms? O(1) log(x/y) = log(x) - log(y) = log(answer) answer = 10 ^ log(answer)

7

Anonymous

Jan 16, 2014

why not just a * b^(-1) :-)

3

Anonymous

Aug 19, 2012

This can be done in a recursive function, the following code is in Python. # get result of a/b without using a "divide" operator def div(a,b): if a < b: return 0 else: return div(a-b, b)+1 This is how human being do the division naturally, however, the running time of this is O(n/m), where n is the size of a, and m is the size of b, which means, O(n/m) is guaranteed to be less than O(n), when m is larger than 1. -Maxim

2

Anonymous

Apr 10, 2017

Convert the number to divide into the base of the number that you are dividing with and then shift the 'bits' to the right by 1 then convert back to decimal

2

Anonymous

Dec 11, 2014

// Write a function that divides one number by another, without using the division operator, // Assume that x%y = 0 // O(log n) (function() { 'use strict'; var divide = function(x, y) { var xLength = (x + '').length; var i = 0; var result = 0; var xAry = ('' + x).split(); var xStart = ''; for (i = 1; i = y) { xStart -= y; result = parseInt(result, 10) + 1; } } } return result; }; console.log(divide(1000, 4)); })();

Anonymous

Jan 23, 2013

Totally agree with Vasil. Other option: Long Division Algorithm. O(log n) anyway.

Anonymous

Sep 2, 2012

The answer above is still O(n). We can use binary search and find the answer in the interval [1,a] and use multiplication operator.

2