-4

I need to multiply two integers without using multiplication or division operators, any built in Multiply functions, or loops.

I have managed to do multiplication with with a loop, but I don't get how to do so without loops.

Here is my solution with a loop:

Public Double(Double x, Double y)
{
 Double Result;
 Result =0;
 If(x==0 || y==0)
 {
   Result = 0;
  }
 else
 {
  for(int i=0; i<=y; i++)
   {
     Result = Result + x;   
   }
 }
        return Result;
}
Servy
  • 202,030
  • 26
  • 332
  • 449
K.Z
  • 5,201
  • 25
  • 104
  • 240

2 Answers2

0

You can do something like below in your function

        List<int> temp = new List<int>();
        temp.AddRange(Enumerable.Repeat(x,y));

        var result = test.Sum();

where your 'y' variable would be an integer count. However I'm not sure what exactly you are looking for

Maddy
  • 774
  • 5
  • 14
0

I need to multiply two integers without using multiplication or division operators, any built in Multiply functions, or loops.

Reading the condition of your question, I think that the idea here is to use a smarter way for calculation, for example bitwise operations.

Based on the answers in How to perform multiplication, using bitwise operators? I suggest the following solution for your problem:

    public int MultiplyBitwise(int a, int b)
    {
        int product = 0;
        while (b > 0)
        {
            product += ((b & 1) > 0) ? a : 0;
            a <<= 1;
            b >>= 1;
        }

        return product;
    }
Community
  • 1
  • 1
Tanya Petkova
  • 155
  • 1
  • 1
  • 7