C#的高效算法基于整数幂函数 [英] C# Efficient Algorithm Integer Based Power Function

查看:459
本文介绍了C#的高效算法基于整数幂函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在看<一href="http://stackoverflow.com/questions/101439/the-most-efficient-way-to-implement-an-integer-based-power-function-powint-int">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.

这篇关于C#的高效算法基于整数幂函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆