Hardware Reference
In-Depth Information
movb
#16,lpcnt,SP
; initialize loop count to 16
iloop
ldd
mask,SP
; get the mask
oraa
sar,SP
; set a bit in sar to 1
orab
sar 1 1,SP
; ''
std
temp,SP
; save a copy of your guess
tfr
D,Y
; compute sar * sar
emul
; ''
cpy
q_hi,SP
; is our guess correct?
bhi
nextb
; ''
cpd
q_lo,SP
; ''
bhi
nextb
; ''
ldd
temp,SP
; yes, our guess is correct
std
sar,SP
; so, transfer temp to sar
nextb
lsr
mask,SP
; shift mask to the right one place
ror
mask 1 1,SP
; ''
dec
lpcnt,SP
bne
iloop
ldd
sar,SP
; put sar in D as the approximated square root
leas
locVar,SP
; deallocate local variables
puly
pulx
rts
;
org
$FFFE
; uncomment this line for CodeWarrior
;
dc.w
start
; uncomment this line for CodeWarrior
end
This subroutine will find the exact square root if the given number has one. If the given
number does not have an exact integer square root, then the number returned by the subroutine
may not be the closest approximation. The algorithm in Figure 4.12 will compute a sar that
satisfies the relationship sar * sar , q. This may have the undesirable effect that the last sar
value may not be as close to the real square root as is the value of sar 1 1. However, this can be
fixed easily by comparing the following two expressions:
1. ( sar 1 1) 2 2 q
2. q 2 sar 2
If the first expression is smaller, then ( sar 1 1 ) is a better choice. Otherwise, we should
choose sar as the approximation to the real square root. This will be left as an exercise problem.
We will make the subroutine findsqr into a file ( findsqr.asm ) so that it can be reused in the next
example.
4.7.3 Subroutine for Prime Testing
Testing whether a number is a prime may not be extremely useful for embedded applica-
tions. However, it can serve as a good example for software reuse.
The most efficient method for testing whether a number is a prime is to divide the number
by all the prime numbers from 2 to its integral square root. Since the prime numbers from 2
to the square root of the given number are not available, we will be satisfied with dividing the
given number by all the integers from 2 to its integral square root.
 
Search WWH ::




Custom Search