Assembly factorial

factorial with for loop

Page 1 of 1

2 Replies - 5070 Views - Last Post: 26 April 2010 - 05:25 AM

#1 szacik  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 25-April 10

Assembly factorial

Posted 25 April 2010 - 04:15 PM

Hi everyone, I have problem with this factorial. I am trying to do it with for loop, but this code multiplying the two last numbers. For 3! the result is correct but for 4! and more result is not correct. Do you have any ideas where is bug? Thanks a lot.

.data   # Data declaration section
promptInt: .asciiz "Write number of factorial"
answer: .asciiz "Factorial: \n"
        .text

main:           # Start of code section
        #display promptInt
        li $v0, 4
        la $a0, promptInt
        syscall
        
        #giving number
        li $v0, 5
        syscall
        move $s1, $v0
        
        #for loop ------------------------
        li $s0, 0               #int i=0
        for_loop:               #loop starting 
        
        addi $t0, $s0, 1        #t0=s0+1
        mul $t1, $t0, $s0       #t1=t0*s0
        
                        
        addi $s0, $s0, 1        #s0++
        blt $s0, $s1, for_loop  #s0>s1
        #----------------------
        move $s2, $t1
        
        #show result
                li $v0, 1
                move $a0, $s2
                syscall
        
        
        
#END OF PROGRAM


Is This A Good Question/Topic? 0
  • +

Replies To: Assembly factorial

#2 wildgoose  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 67
  • View blog
  • Posts: 468
  • Joined: 29-June 09

Re: Assembly factorial

Posted 26 April 2010 - 01:56 AM

Have you traced your code flow?

You increment your value, you do a multiply between two adjacent numbers, but throw it away.

Shouldn't it be
5! = 2 * 3 * 4 * 5

So tot = 1
  s = 2

  tot = tot * s
  s++
  ( s < 5) loop



...Not...
0*1
1*2
2*3
3*4
4*5
Was This Post Helpful? 1
  • +
  • -

#3 szacik  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 25-April 10

Re: Assembly factorial

Posted 26 April 2010 - 05:25 AM

Thanks, I must focus on syntax of Assembly.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1