Interview Question
Java DevelopersCountry: UK
Interview Type: Written Test
there are many pitfalls in that case.What about 100! * 100! ?
@eugene.yarovoi: I think your case can be easily handled by taking absolute values and checking the signs?If two negatives then result will be positive and if one negative then result will be negative.
You may also use recursive function:
Multiply(a, b)
{
if(b == 0)
{
return a;
}
else
{
return Multiply(a++, b--);
}
}
However, I think b-- is an arithmetic operation...
By using post increment and post decrement operator a and b will never change its value as in post operation first of all it assign value than increment.
so your code will be in infinite loop.
example
b=5
a = b++;
a =5 and b =6 will return;
And if go with logic it will just add b's value to a.
example
a =5 , b =6
return 11 only
required is 30.
this is almost correct, but even if you fix the post-incrementation bug, the logic still isnt there.
you are stating in your code that addition is recursive and decrements the value to be added along with the times it is added. this is false.
actually, it should be stated as recursive addition decrementing only the times added.
the inductive base case is when the first value is 1, which returns the first value, which is how multiplication is defined (i.e. 1*x = x)
example code that works in java
static int mult(int a, int b)
{
if(b == 0 || a == 0)
{
return 0;
}
else if(b == 1)
{
return a;
}
else
{
return a + mult(a, b - 1);
}
}
You can also claim this code works because it is adding -1 not taking away 1.
you also should take into account when the values are 0 -> 0
public static int multiply(int n, int m) {
int temp = n;
for(int i = 0; i < (m-1); i++) {
for(int j = 0; j < n; j++) {
temp++;
}
}
return temp;
}
//hope this would satisfy for all multiplication operands
#include<stdio.h>
int main()
{
int n,i,j,m,result=0;
printf("enter the two numbers for product:\n");
scanf("%d%d",&n,&m);
for(i=1;i<=abs(m);i++)
for(j=1;j<=abs(n);j++)result++;
if(((m<0)&&!(n<0))||(!(m<0)&&(n<0))){
result=(~result);result++;}
printf("thus the product of two numbers is :%d",result);
return 0;
}
here no arithmetic opertion, I think all are improper.
the road using ++/+ is arithmetic, how about logic bitwise operation
Int K= 1;
unsigned int p=1;
Int i=1; j=1;
For( i= 1;i<=m;i++ )
For( J=1 ; j<=n; J++)
p<<1;
k+=p;
System.out.println(" M*N = " + k )
does that sound the right answer
In C logic will be like this:
- Vipan k Verma May 21, 2013int func(int a,int b)
{
int result=0,i,j;
for(int i=0;i<b;i++)
{
for(int j=0;j<a;j++)
{
result++;
}
}
return result;
}