C#的高效算法基于整数幂函数高效、整数、算法、函数

2023-09-11 06:23:25 作者:淡唱、悲傷)

我在看http://stackoverflow.com/questions/101439/the-most-efficient-way-to-implement-an-integer-based-power-function-powint-int.

这是他们得到了答案。

我想使它成为C#的工作,但我得到比较INT为bool而这一切其他的东西。 。 。我想不通为什么他们比较和放大器; 1并不意味着与真的吗?什么是该点。这似乎效率不高。

I am trying to make it work for C# but I am getting comparing int to bool and all this other stuff. . . and I can't figure out why they are comparing & 1 wouldn't that mean and true? What is the point of that. It doesn't seem efficient.

 int ipow(int base, int exp) 
 { 
     int result = 1; 
     while (exp) 
     { 
         if (exp & 1) 
             result *= base; 
         exp >>= 1; 
         base *= base; 
     } 

return result; 

}

我在做EXP ==在比较但这1仍然存在,我不知道我是否需要它。

I am doing exp == on the compare but that 1 is still there and I don't know if I need it.

是否有人知道,在1:如果(EXP&安培; 1)是什么?或者,如果我需要它?我看不到使用。

Does someone know what the 1 in "if (exp & 1) " is for? Or if I need it? I can't see the use.

推荐答案

基本上在C和C ++的条件,如果/当是如果EX pression非零。

Basically in C and C++, the condition for if/while is "if the expression is non-zero".

因此​​,在这种情况下,你会想:

So in this case you'd want:

while (exp != 0)

if ((exp & 1) != 0) // If exp is odd

您会也想避免使用关键字基础:)

You'd also want to avoid using the keyword base :)

我没有检查该算法是否将工作在C#中,但应该至少可以帮助你获得了一步。

I haven't checked whether the algorithm will work in C#, but that should at least help you get one step further.