0

Can anyone make sense of this code?? Have no idea how this algorithm knows when to stop.

For example, when the number is 144 -- how does it know to stop dividing by two? Why does it stop at 12 and not 6??

 .ent isqrt
  isqrt:
  //v0 - return / root
  //t0 - bit
  //t1 - num
  //t2,t3 - temps

  //Store parameter
  sw a0, 0(fp)

  //Make stack frame for output_string
  addiu sp, sp, -32
  sw ra, 28(sp)
  sw fp, 24(sp)
  move fp, sp

  move  v0, zero        //initalize return
  move  t1, a0          //move a0 to t1

  addi  t0, zero, 1

  sll   t0, t0, 30

isqrt_bit:
  slt   t2, t1, t0     //num < bit
  beq   t2, zero, isqrt_loop
  nop

  srl   t0, t0, 1       //Divide by 4

  j     isqrt_bit
  nop

isqrt_loop:
  beq   t0, zero, isqrt_return
  nop

  add   t3, v0, t0     //t3 = return + bit

  slt   t2, t1, t3
  beq   t2, zero, isqrt_else
  nop

  srl   v0, v0, 1       //Divide by two

  j     isqrt_loop_end
  nop

isqrt_else:
  sub   t1, t1, t3     //num -= return + bit
  srl   v0, v0, 1       //Divide by two
  add   v0, v0, t0     //return + bit

 isqrt_loop_end:
      srl   t0, t0, 2       //Divide by 4
      j     isqrt_loop
      nop

  isqrt_return:

    move sp, fp
    lw ra, 28(fp)
    lw fp, 24(fp)
    addiu sp, sp, 32

  jr  ra
  nop

.end isqrt
Lanorkin
  • 6,802
  • 2
  • 34
  • 56
MrPickle5
  • 496
  • 4
  • 8
  • 27
  • 1
    That code appears to generate incorrect results, so I wouldn't worry too much about making sense of it. It gets some answers right, but e.g. for an input of 144 I got the result 16. – Michael Nov 15 '13 at 10:19

1 Answers1

2

the beq instruction exits the loop

it's compiled from C in this answer: finding square root of an integer on mips assembly

Community
  • 1
  • 1
gordy
  • 8,350
  • 1
  • 27
  • 40
  • Yes, but why is the code dividing t0 by four?? I just don't understand how this algorithm works. – MrPickle5 Nov 15 '13 at 06:25
  • it's easier to study the C code - there are incorrect comments in this asm. srl .., 1 is shifting right by 1 (>> 1 in C) but it is commented as divide by 4 here – gordy Nov 15 '13 at 18:20