Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ;
- ; Hailstone numbers:
- ; http://en.wikipedia.org/wiki/Collatz_conjecture
- ;
- ; Start with some positive integer term.
- ; If term is odd, multiply by 3 and add 1.
- ; If term is even, divide by 2.
- ; Repeat until term is 1.
- ;
- ; Read initial term from memory location N.
- ; Write the largest term encountered back to N.
- ;
- ; Note:
- ; enable forwarding on simulator
- ; enable branch delay slot on simulator
- ;
- ; 2097 cycles.
- ;
- ; 1438
- ;
- .data
- N: .word 27 ; initial term/value
- .text
- ld r1,N(r0) ; r1 = N
- loop: andi r3,r1,1 ; is the current term (r1) odd or even?
- beqz r3,even ; if statement: branch if term is even (r1 % 2 == 0) (r3 == 0)
- ;nop ; branch delay slot
- ; if branch
- odd:
- dsll r11,r1,1 ; * 3
- dadd r1,r1,r11 ; finished off multiplication
- daddi r1,r1,1 ; r1 = r1 + 1
- ;nop ; branch delay slot
- slt r3,r10,r1 ; compare current term with maximum
- beqz r3,skip ; if not new maximum, then skip
- ;nop ; branch delay slot
- dadd r10,r0,r1
- j skip
- ; else branch
- even: dsrl r1,r1,1 ; divide by 2 (r1 = r1 >> 1)
- ; drop through to instruction following if statement
- j skip ; we skip as the number / 2 is not going to be a maximum
- skip: slti r3,r1,2 ; test for finished (r1 < 2)
- beqz r3,loop ; branch back to loop if not finished (if 2 <= r1, if r3 == 0)
- ;nop ; branch delay slot
- sd r10,N(r0) ; store maximum at end
- halt ; done -- maxhail(N) is now in memory location N
- ; if the initial term (N) was 27, then the hexadecimal value
- ; in N -- the maximum term encountered -- should
- ; be 0x2410 (decimal 9232)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement