汇编程序(TASM)计算上升到n的幂(m ^ n)

时间:2013-04-10 04:05:38

标签: assembly x86

我已编写了一半的程序。问题是我不知道如何编码数学运算部分将m提升到n (m^n)的幂。那么,作为初学者,我有什么建议吗?

.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)?

2 个答案:

答案 0 :(得分:2)

您可以重复乘法,如下所示:

int result = 1;  while (exp-->0) { result *= base; } return result;

或者,你可以/应该用它的二进制表示来处理指数:

5^13 = 5^(0b1101) = 1*(5^1)*(5^4)*(5^8)

因此可以重复 square 基础5:5的副本 - > 25 - > 625 - > 390625并将那些在指数的二进制表示中设置了相应位的项相乘。

对于16位算术来说,这可能有些过分,但如果您的教授要求您执行模块化指数(如非对称加密中所使用的那样),它会很方便。

这两种方法都需要使用条件跳转:

有条件地重复cx次操作的次数:

         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

要测试正在设置的位,可以执行

         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 ==如果不等于跳转也会测试零标志。 它是Jump if Not Zero的同义词。

答案 1 :(得分:0)

计算整数幂只是一系列乘法。例如,5 ^ 2 == 5 * 5,2 ^ 3 == 2 * 2 * 2,依此类推。

因此,一个简单的乘法循环就足够了:

mov bx,5   ; m
mov cx,3   ; n
mov ax,1   ; Initial result, i.e. m^0
power:
    jcxz power_done
    mul bx
    loop power
power_done:
; ax now contains m^n

请注意,我的示例代码不处理结果大于16位的情况(除了最后一次迭代时隐式)。它也不处理m的负值。如果你需要的话,我会把它作为练习让你查找指令集参考来解决这些问题。

相关问题