Advertisement
KillianMills

Hail4.s

Oct 24th, 2014
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. ;
  2. ; Hailstone numbers:
  3. ; http://en.wikipedia.org/wiki/Collatz_conjecture
  4. ;
  5. ; Start with some positive integer term.
  6. ; If term is odd, multiply by 3 and add 1.
  7. ; If term is even, divide by 2.
  8. ; Repeat until term is 1.
  9. ;
  10. ; Read initial term from memory location N.
  11. ; Write the largest term encountered back to N.
  12. ;
  13. ; Note:
  14. ; enable forwarding on simulator
  15. ; enable branch delay slot on simulator
  16. ;
  17. ; 2097 cycles.
  18. ;
  19. ; 1438
  20. ;
  21.  
  22. .data
  23.  
  24. N: .word 27 ; initial term/value
  25.  
  26. .text
  27.  
  28. ld r1,N(r0) ; r1 = N
  29.  
  30. loop: andi r3,r1,1 ; is the current term (r1) odd or even?
  31. beqz r3,even ; if statement: branch if term is even (r1 % 2 == 0) (r3 == 0)
  32. ;nop ; branch delay slot
  33.  
  34. ; if branch
  35. odd:
  36. dsll r11,r1,1 ; * 3
  37. dadd r1,r1,r11 ; finished off multiplication
  38.  
  39. daddi r1,r1,1 ; r1 = r1 + 1
  40. ;nop ; branch delay slot
  41. slt r3,r10,r1 ; compare current term with maximum
  42. beqz r3,skip ; if not new maximum, then skip
  43. ;nop ; branch delay slot
  44. dadd r10,r0,r1
  45. j skip
  46.  
  47. ; else branch
  48. even: dsrl r1,r1,1 ; divide by 2 (r1 = r1 >> 1)
  49. ; drop through to instruction following if statement
  50. j skip ; we skip as the number / 2 is not going to be a maximum
  51.  
  52.  
  53. skip: slti r3,r1,2 ; test for finished (r1 < 2)
  54. beqz r3,loop ; branch back to loop if not finished (if 2 <= r1, if r3 == 0)
  55. ;nop ; branch delay slot
  56.  
  57. sd r10,N(r0) ; store maximum at end
  58.  
  59. halt ; done -- maxhail(N) is now in memory location N
  60. ; if the initial term (N) was 27, then the hexadecimal value
  61. ; in N -- the maximum term encountered -- should
  62. ; be 0x2410 (decimal 9232)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement