Amazon Interview Question
Software Engineer / Developersyour code gives, 2/1 = 1, 10/2 = 4
maybe count = 0 is a better idea?
Worst case complexity : O(numerator/denominator)
Do we have to give output in integer or decimal points as well. Integer its straight forward subtraction
Math.pow(Math.E, Math.log(num) - Math.log(denom)) /* e^{ln(num) - ln(denom)} */
Suppose,
x = num/denom
Taking natural log,
ln(x) = ln(num/denom) = ln(num) - ln(denom)
e^{ln(x)} = e^{ln(num) - ln(denom)}
Answer,
x = e^{ln(num) - ln(denom)}
#include <stdio.h>
int division(int x, int y);
int main()
{
int numerator = 0;
int denominator = 0;
int res = 0;
printf("Enter numerator and denominator: \n");
scanf("%d%d",&numerator,&denominator);
if(denominator == 0)
{
printf("Denominator can't be zero in a division..\n");
return 1;
}
res = division(numerator, denominator);
printf("Integer Division Result= [%d]\n",res);
return 0;
}
int division(int numerator,int denominator)
{
int count = 0;
if(numerator < denominator)
{
return count;
}
while(numerator > denominator)
{
numerator = numerator - denominator;
count++;
}
}
#include <iostream.h>
#include <math.h>
using namespace std;
float divide(float,float);
int main()
{
while(1)
{
float num, denom;
cout<< "Enter numerator: ";
cin >> num;
cout<< "Enter denominator: ";
cin >> denom;
float x;
cout<< divide(num,denom)<< endl;
}
}
float divide(float num, float denom)
{
return (num*pow(denom,-1));
}
we can use binary search to solve this problem. The already existing solutions presented here run in O(numerator/deno). If denominator is 1 then the worst case time complexity will be O(numerator) which is very bad. The solution using the binary search can solve the problem in O(log(numerator)).
The problem can be restated as follows. Find the largest number x such that q*x<=p.Here I assume that p,q are positive numbers. The following is the code.
int p,q;
int division(int start=0,int end = p){
if(start>end)
return -1;
int mid = (start+end)>>1;
if(q*mid<=p)
return max(mid,division(mid+1,end));
else
return division(start,mid-1);
}
A solution using bit manipulation:
The following code works for positive numbers. When the dividend or the divisor or both are negative, have flags to change the sign of the answer appropriately.
int divi(long long m, long long n)
{
if(m==0 || n==0 || m<n)
return 0;
long long a,b;
int f=0;
a=n;b=1;
while(a<=m)
{
b = b<<1;
a = a<<1;
f=1;
}
if(f)
{
b = b>>1;
a = a>>1;
}
b = b + divi(m-a,n);
return b;
}
int divide(int numerator, int denomenator)
- abcd November 08, 2010{
int count = -1;
do
{
count++;
numerator = numerator - denomenator;
} while(numerator>0)
return count;
}