仅通过加法计算指数
我们正在编写一个非常简单的程序,在我们为类构建的处理器上执行。它没有乘法或除法的能力。不过,我们确实支持加法、减法、与、或以及循环控制分支(如果您熟悉 MIPS,则支持等于分支)。我们认为在其上运行的简洁程序应该是某种 x^n 程序。当然,这些数字必须进行硬编码,但考虑到我们处理器的限制,这现实吗?
是否有指数的仅加法计算? 谢谢。
We're writing a very simple program to execute on a processor we've built for a class. It doesn't have the capability to multiply or divide. We do however, had support for addition, subtraction, and, or, and branching for loop control (like branch on equal if you are familiar with MIPS). We were thinking a neat program to run on it would be some sort of x^n program. Of course, those numbers would have to be hardcoded, but given the limitations of our processor, is it realistic?
Is there an addition only calculation for exponents?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
对于小整数,为什么不呢?
首先,使用重复加法实现乘法。然后,使用重复乘法实现 pow()。它会很慢,但会很好地工作。
有一种更快的求幂算法,称为平方求幂。但是,鉴于您没有快速乘法,我不确定它是否值得 - 您可能想首先实现快速乘法算法。
For small integers, why not?
First, implement multiply using repeated addition. Then, implement pow() using repeated multiplication. It will be slow, but it will work fine.
There is a faster algorithm for exponentiation, called Exponentiation by Squaring. However, given that you don't have a fast multiply, I'm not sure it's worth it - you might want to first work on implementing a fast multiplication algorithm.
与 dmazzoni 的 c 风格语法响应一致:
In line with dmazzoni's respone in c style syntax:
与 Aequitarum 的解决方案类似,但对幂使用重复平方,对乘法使用重复加倍。对于较大的 x,y 应该更快:
Like Aequitarum's solution, but uses repeated squaring for powers and repeated doubling for multiplies. Should be faster for large x,y:
这是非常现实的。几年前,处理器还没有可以执行乘法和除法等高级运算的 ALU。
乘法通常使用移位和加法来完成。这是一些伪汇编:(
请注意,两个字节值相乘的结果是一个两个字节值。)
一旦有了乘法,您就可以循环计算幂。
使用说明:
It's very realistic. It's not so many years back that processors didn't have an ALU that could do any advanced operations like multiplication and division.
Multiplication is usually done using shifting and adding. Here's some pseudo-assembly:
(Note that the result of multiplying two byte values is a two byte value.)
Once you have a multiplication, you can just loop to calculate power.
instructions used:
您可能会发现有关 乘法 ALU 的相关维基百科文章。通过加法和按位运算(与和或),您可以按一位一步实现乘法,而不必按照较小运算符的大小进行多次加法。
You may find the Wikipedia article on Multiplication ALU relevant. With addition and bitwise operations (and and or), you can implement multiplication in one step per bit, rather than having to add as many times as the magnitude of the smaller operator.
指数 n 的 k 次方:
exponent n to power of k: