Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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

like image 543
user1211185 Avatar asked Oct 01 '13 13:10

user1211185


People also ask

How do you multiply without multiplication signs?

By making use of recursion, we can multiply two integers with the given constraints. To multiply x and y, recursively add x y times. Approach: Since we cannot use any of the given symbols, the only way left is to use recursion, with the fact that x is to be added to x y times.

How do you multiply decimals without?

To multiply decimals, first multiply as if there is no decimal. Next, count the number of digits after the decimal in each factor. Finally, put the same number of digits behind the decimal in the product.

Can you use i ++ for multiplication?

No, it's not possible. There is no operator like ** in C unlike unary increment ( ++ ) and decrement ( -- ) operators. You should have try i *= i .


2 Answers

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);
like image 150
Jon Egerton Avatar answered Sep 23 '22 04:09

Jon Egerton


Just another way ;)

if (second < 0)
{ 
    second = Math.Abs(second);
    first = (-1) * first;
}
result = Enumerable.Repeat(first, second).Sum();
like image 22
Tim Schmelter Avatar answered Sep 26 '22 04:09

Tim Schmelter