I have the code here but still can not figure out why it can not work why I enter X=2, and N>= 31....
.data
str: .asciiz " Inter X:"
str1: .asciiz " Inter N:"
str2: .asciiz " X to the power of N is : "
.text
main:
la $a0,str
li $v0,4
syscall
li $v0,5
syscall
move $t0,$v0
la $a0,str1
li $v0,4
syscall
li $v0,5
syscall
move $a1,$v0 #$a1=N
move $a0, $t0 #$a0=X
jal Power
move $s0,$v0
la $a0,str2
li $v0,4
syscall
move $a0,$s0
li $v0,1
syscall
li $v0,10
syscall
Power: addi $sp,$sp,-4
sw $ra,0($sp)
bne $a1,$zero, Else`
addi $v0,$zero,1
addi $sp, $sp,4
jr $ra
Else: bne $a1,1, Else1
add $v0,$zero, $a0
addi $sp,$sp,4
jr $ra
Else1: move $t1,$a1
andi $t0, $t1,1 #check if N is even or odd
bne $t0,$zero, Else2 #odd goto Else2
srl $a1, $a1,1 #even N/2
jal Power #recursive
mul $v0,$v0,$v0 # Power(x,n/2)*Power(x,n/2)
lw $ra, 0($sp)
addi $sp,$sp,4
jr $ra
Else2: addi $a1,$a1,-1 #odd X*power(x,n-1)
jal Power
lw $ra, 0($sp)
addi $sp,$sp,4
mul $v0,$v0,$a0
jr $ra
ANd here the problem "Problem
Write a program in MIPS which computes x^n for nonnegative integers x and n. Your program must contain a recursive procedure which executes the following recursive definition of x^n:
X^n = 1 if n = 0
X^n = x if n =1
X^n = (x^(n/2)) * (x^(n/2)) if n > 1 and n is even
X^n = x * (x^(n-1)) if n > 1 and n is odd
Recall that an even number can be divided by 2 using the shift right logical instruction (srl). So if the integer n is even and contained in register $t0, then
srl $t1, $t0, 1
will result in n/2 being placed in register $t1. Also, you can check if a number is even by checking the value of its least significant bit. The least significant bit can be isolated by using the immediate instruction with . That is
andi $t1, $t0, 1
will result in $t1 containing 1 (i.e. a string of 31 zeros followed by a 1) if the least significant bit of $t0 is 1 and 0 (i.e. a string of 32 zeros) otherwise.
If this procedure were written in a highlevel programming language, it might look something like this:
pow(int x, int n) {
if( n == 0 ) {
return 1; }
else if( n == 1 ) {
return x; }
else if( (n % 2) == 0 ) {
int temp = pow(x,n/2);
return temp*temp;
}
else {
return x*pow(x, n }
}
Your program should prompt the user to input x and n, and then it should print the result. You may use the
"
Could someone show me??