汇编程序(TASM)计算提高m到n的幂(m ^ n) [英] assembler program (TASM) calculate raise m to the power of n (m^n)
问题描述
我已经编码了程序的一半.问题是我不知道如何编码数学运算部分是将m
提高到n (m^n)
的功效.那么,对于我的初学者有什么建议吗?
I have already coded half of the program. The problem is I don't know how to code math operation part is raise m
to the power of n (m^n)
. So, any advise for me as a beginner?
.MODEL SMALL
.DATA
greet db 13,10, "Welcome to Simple Calculator: Raise m to the power n. $"
msg1 db 13,10, 0AH,0DH,"Please enter integer (m:-99 to 99): $"
m db 3,4 dup(?)
msg2 db 10,13, 0AH,0DH,"Please enter power (n:1 to 9): $"
n db 3,4 dup(?)
total db 10,13, "Answer: $"
.CODE
START:
mov ax, seg greet
mov ds, ax
mov dx, offset greet
mov ah, 09h ;Display message
int 21h
mov ax, seg msg1
mov ds, ax
mov dx, offset msg1
mov ah, 09h
int 21h ;Print a message
mov ah, 0ah
mov dx, offset m
int 21h ;Get 'm' value
n_POWER:
mov ax, seg msg2
mov ds, ax
mov dx, offset msg2
mov ah, 09h
int 21h ;Print a message
mov ah, 0ah
mov dx, offset n ;Get 'n' value
int 21h
mov ax, m
mov n, ax
mul ax, n
mov total, n
finish:
mov ah, 09h ;Display message
int 21h
mov ax,4c00h ;Return control to DOS
int 21h
end start
此外,我如何从用户那里获得否定输入(例如-99
)?
Also, how can I get the negative input from the user (eg. -99
) ?
推荐答案
您可以按照以下方式重复乘法:
You can either repeat the multiplication as in:
int result = 1; while (exp-->0) { result *= base; } return result;
或者,您可以/应该以二进制表示形式处理指数:
or, you can / should treat the exponent in it's binary representation:
5^13 = 5^(0b1101) = 1*(5^1)*(5^4)*(5^8)
因此,一个人可以重复对基数5:5-> 25-> 625-> 390625进行平方的副本,并将那些在指数的二进制表示形式中具有相应位的项相乘.
One can thus repeatedly square a copy of the base 5: 5 -> 25 -> 625 -> 390625 and multiply those terms that have a corresponding bit set in the binary representation of the exponent.
这对于16位算术来说可能是过高的,但是如果您的教授要求您改为执行模块化指数(如非对称密码术中所用),这将很方便.
This may be overkill for 16-bit arithmetic, but it'll be handy if your professor asks you to perform a modular exponentation instead (as used in asymmetric cryptography).
这两种方法都需要使用有条件的跳转:
Both methods require using conditional jumps:
要有条件地重复cx
个操作,只需简单地执行一次操作即可:
to conditionally repeat cx
number of operations one simply does:
mov cx, 13
label: nop // put your block of code here
nop
loop label; // The instruction at label will be executed 13 times
// and cx will end up being zero
要测试是否已设置,可以做
To test a bit being set, one can do
mov dx, 13 ;; let's have the exponent here
label: test dx, 1 ;; check if the first bit is zero
;; test performs bitwise _and_ between the operand
;; and sets ZERO flag (among other things)
jz notset
nop ;; insert here the statements to be executed
;; when the bit in the exponent is set
notset: shr dx, 1 ;; shift out the least significant bit -- this also
;; sets the ZERO_FLAG if dx goes to zero
;; (and it eventually does)
jne label; ;;
顺便说一句. JNE ==如果不等于也测试零标志,则跳转. 如果不为零,则表示跳转.
btw. JNE == Jump if Not Equal also tests for zero flag. It's synonymous to Jump if Not Zero.
这篇关于汇编程序(TASM)计算提高m到n的幂(m ^ n)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!