
uses console

function btkMul(int *a,*b,*c,q)
===============================
dword i,j,k,ca,cy,cyy,oo,oq
dword aa at @a
dword bb at @b
dword cc at @c
for i=1 to q*2
  aa=0 : @aa+=4 'clearing accum
next
oo=q*4-4 'shifting offset
oq=oo    'fixed offset
for i=1 to q
  @cc=@c+oo     'multiplier
  @bb=@b+oq     'value
  @aa=@a+q*4+oo 'accum
  cyy=0         'clear accum carry
  cy=0          'clear multiply carry
  for j=1 to q
    k=bb*cc+cy ': cy=0
'mov ecx,10000
'div ecx
'mov cy,eax
'mov k,edx
    'if k>=10000 then
      cy=k\10000
      k=edx 'remainder after cpu division
    'end if
    k=k+aa+cyy : cyy=0
    if k>=10000 then k-=10000 : cyy=1
    aa=k
    @aa-=4
    @bb-=4
  next
  aa=cyy+cy 'final carries
  oo-=4 'shift left for next line mul
next
end function


function btkCompare(int *b,*c,i) as int
=======================================
dword bb at @b
dword cc at @c
while i
  i--
  if bb>cc then return 1
  if bb<cc then return -1
  @bb+=4
  @cc+=4
wend
end function


int nm[32],nt[32],nr[32] 'result,target,root

'square roots
=============

'square root of 2
'using binary step approximator
indexbase 0
int i
for i=0 to 15 : nr[i]=0 : next 'clear nr
nt[0]=200   'target value representing 2
nr[0]=1410  'estimate of square root
int b,c,i
int n at @nr 'strider for square root digits
b=8192 '0x2000 'shifting bit setter
i=16
while i
  n or= b 'set bit
  btkMul nm,nr,nr,16
  c=btkCompare(nt,nm,32)
  if c<0 then 'too large
    n xor= b 'clear bit
  end if
  shr b 'next bit down
  if b=0 then
    i--
    b=8192
    @n+=4 'next 10k down
  end if
wend

'display digits in groups of four
print "square root of 2" cr
for i=0 to 15
  print i tab mid("000"+str(nr[i]),-4) cr
next
print cr

'square root of 5 --> phi
'using binary step approximator
indexbase 0
int i
for i=0 to 15 : nr[i]=0 : next 'clear nr
nt[0]=500   'target value representing 5
nr[0]=2200  'estimate of square root
int b,c,i
int n at @nr 'strider for square root digits
b=8192 '0x2000 'shifting bit setter
i=16
while i
  n or= b 'set bit
  btkMul nm,nr,nr,16
  c=btkCompare(nt,nm,32)
  if c<0 then 'too large
    n xor= b 'clear bit
  end if
  shr b 'next bit down
  if b=0 then
    i--
    b=8192
    @n+=4 'next 10k down
  end if
wend


'convert to little phi
nr[0]-=1000 'subtract 1
'shift right 'divide by 2
addr esi,nr
mov ecx,16
clc
pushf
(
 xor edx,edx
 popf
 (
  jnc exit
  mov edx,5000
 )
 shr dword [esi] 'shift right carry
 pushf
 add [esi],edx
 add esi,4
 dec ecx
 jg repeat
)
popf


'display digits in groups of four
print "phi" cr
for i=0 to 15
  print i tab mid("000"+str(nr[i]),-4) cr
next

'61803398874989484820458683436563811772030917980576286213544862270526046281890

waitkey
 

 
 


