How to multiply decimal numbers without using the multiplication sign (*)

Can someone suggest me a way to multiply decimal numbers without using the multiplication sign (*). I know this sounds like homework, but I just want to know how to achieve this. I have already done this for positive and negative integers, as shown below:

int first = 2;
int second =2;
int result = 0;
bool isNegative = false;

if (first < 0)
{
    first = Math.Abs(first);
    isNegative = true;
}
if (second < 0)
{
    second = Math.Abs(second);
    isNegative = true;
}

for (int i = 1; i <= second; i++)
{
    result += first;
}

if (isNegative)
    result = -Math.Abs(result);

Want to multiply this by decimal places:

decimal third = 1.1;
decimal fourth = 1.2;

thanks

+4
source share
5 answers

A little cheating, but if the task strictly applies to all forms of multiplication (and not just to the operator *), then divide it into the opposite:

var result = first / (1 / (decimal)second);
+12
source

Another way :)

if (second < 0)
{ 
    second = Math.Abs(second);
    first = (-1) * first;
}
result = Enumerable.Repeat(first, second).Sum();
+6
source

* Decimal.Multiply.

:

decimal first = -2.234M;
decimal second = 3.14M;

decimal product = Decimal.Multiply(first, second);
+2

Strictly with "*"? I would take note of the XOR operator. Although I know that this code is not much different from OP.

int first = 2;
int second =2;
int result = 0;
bool isNegative;

isNegative = (first<0)^(second<0);

first = (first<0)?Math.Abs(first):first;    
second = (second<0)?Math.Abs(second):second;

for (int i = 1; i <= second; i++)
    result += first;

result = (isNegative)?-Math.Abs(result):result;
+1
source

Here's a different approach, using journal rules, for completeness:

decimal result = (decimal)Math.Exp(
    Math.Log((double)third) + Math.Log((double)fourth));

It will not work for all decimal places (in particular, not for negative numbers, although it can be expanded to detect them and get around them), but it is still interesting.

0
source

All Articles