Division algorithm

General FreeBASIC programming questions.
Post Reply
hhr
Posts: 211
Joined: Nov 29, 2019 10:41

Division algorithm

Post by hhr »

This one seems to work well. But the function is not optimized:

Code: Select all

Function DivMod(Byref n As Ulongint, Byref d As Ulongint, Byref r As Ulongint = 0) As Ulongint
   If d = 0 Then Print "Division by zero" : Sleep : End
   Dim As Ulongint q
   r = 0
   Dim As Byte i
   For i = 63 To 0 Step -1
      r Shl= 1
      If Bit(n,i) Then r = Bitset(r,0)
      If r >= d Then
         r -= d
         q = Bitset(q,i)
      End If
   Next i
   Return q
End Function

Randomize
Function Rnd64 As Ulongint
   Return (Culngint(Rnd*(2^32)) Shl 32) Or Culngint(Rnd*(2^32))
End Function

Dim As Ulongint n,d,q,r
Do
   n = Rnd64 Shr Int(Rnd*64)
   d = Rnd64 Shr Int(Rnd*64)
   If n < d Then Swap n,d ''Can be commented out. Should only ensure that n > d.
   If d = 0 Then d = 1 ''Prevents d from becoming zero
   q = DivMod(n,d,r)
   Print "n = ";n
   Print "d = ";d
   Print "q = ";q
   Print "r = ";r
   If q <> (n\d) Then Print "Div error" : Sleep
   If r <> (n Mod d) Then Print "Mod error" : Sleep
   Print "======================="
Loop Until Getkey = 27 ''Esc
Perhaps lines 33 and 34 should be chosen differently. Then one is not dependent on a functioning division.

Code: Select all

   If (q*d+r <> n) Then Print "Div error" : Sleep
   If (r >= d) Then Print "Mod error" : Sleep
Post Reply