[英]How to multiple two positive integers without multiplication or division operators or loops
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;
}
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.您的 'y' 变量将是整数计数。 However I'm not sure what exactly you are looking for但是我不确定你到底在找什么
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.