Reputation: 731
Can anyone suggest me a way to multiply decimal numbers without using multiplication(*) sign. I know it looks like homework thing, but I just want to know how to achieve this. I have already done this for positive and negative integers as 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 for decimals:
decimal third = 1.1;
decimal fourth = 1.2;
Thanks
Upvotes: 5
Views: 3888
Reputation: 20610
Here's another approach, using rules of logs, for the sake of completeness:
decimal result = (decimal)Math.Exp(
Math.Log((double)third) + Math.Log((double)fourth));
It's not going to work for all decimals (in particular not for negative numbers, although it could be extended to detect these and work around them), but it's interesting nevertheless.
Upvotes: 0
Reputation: 627
Strictly with out '*' ? I'd take note of the XOR operator implemented. Although I know this code is not much different to the OP's.
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;
Upvotes: 1
Reputation: 565
The simplest way to multiple two decimals without using the * operator is to use the Decimal.Multiply method.
Example:
decimal first = -2.234M;
decimal second = 3.14M;
decimal product = Decimal.Multiply(first, second);
Upvotes: 2
Reputation: 41539
Bit of a cheat, but if the task strictly relates to all forms of multiplication (rather than just the *
operator), then divide by the reciprocal:
var result = first / (1 / (decimal)second);
Upvotes: 12
Reputation: 460078
Just another way ;)
if (second < 0)
{
second = Math.Abs(second);
first = (-1) * first;
}
result = Enumerable.Repeat(first, second).Sum();
Upvotes: 6