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

编程入门 行业动态 更新时间:2024-10-28 01:14:28
本文介绍了C#的高效算法基于整数幂函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我在看stackoverflow/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#的高效算法基于整数幂函数

本文发布于:2023-11-30 11:14:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649775.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:高效   整数   算法   函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!