home *** CD-ROM | disk | FTP | other *** search
/ PC Users 1998 June / Cd Pc Users 9.iso / prog / inst / baslibs / basmath.bas < prev    next >
Encoding:
BASIC Source File  |  1996-12-18  |  2.1 KB  |  106 lines

  1. Attribute VB_Name = "basMath"
  2. Option Explicit
  3.  
  4. '
  5. '  Converts a number in any base from 2 to 36
  6. '  to a long.
  7. '
  8. '  Note, this doesn't verify if the string
  9. '  is a valid number in the given base.
  10. '
  11. Public Function Base2Long(s As String, ByVal nB As Integer) As Long
  12.    Dim s2 As String
  13.    Dim i As Long
  14.    Dim j As Long
  15.    Dim X As Long
  16.    Dim n As Boolean
  17.    Dim s3 As String
  18.    
  19.    If Len(s) < 1 Then
  20.       Base2Long = 0
  21.       Exit Function
  22.    End If
  23.    
  24.    s2 = UCase(s)
  25.    
  26.    If Left$(s2, 1) = "-" Then
  27.       n = True
  28.       s2 = Right$(s2, Len(s2) - 1)
  29.    Else
  30.       n = False
  31.    End If
  32.    
  33.    j = 1
  34.    X = 0
  35.    
  36.    For i = Len(s2) To 1 Step -1
  37.       s3 = Mid$(s2, i, 1)
  38.       Select Case s3
  39.       Case "0" To "9":
  40.          X = X + j * (Asc(s3) - 48)
  41.       Case "A" To "Z":
  42.          X = X + j * (Asc(s3) - 55)
  43.       End Select
  44.       
  45.       j = j * nB
  46.    Next i
  47.    
  48.    If n Then
  49.       X = -X
  50.    End If
  51.    
  52.    Base2Long = X
  53. End Function
  54.  
  55. '
  56. '  Converts the number n to any base between 2 and 36
  57. '
  58. Public Function Long2Base(ByVal n As Long, ByVal nB As Integer) As String
  59.   Dim s As String
  60.   Dim nD As Integer
  61.   Dim Negative As Boolean
  62.  
  63.   Negative = n < 0
  64.   n = Abs(n)
  65.   
  66.   Do
  67.     nD = n Mod nB
  68.     If nD > 9 Then
  69.        nD = nD + 7
  70.     End If
  71.     
  72.     s = Chr$(48 + nD) & s
  73.     n = n \ nB
  74.   Loop Until n = 0
  75.   
  76.   If Negative Then
  77.     s = "-" & s
  78.   End If
  79.   
  80.   Long2Base = s
  81. End Function
  82.  
  83.  
  84. '
  85. ' Returns true if the number is a prime number.
  86. ' false if it is not.
  87. '
  88. ' This should work reasonably well for small
  89. ' numbers (32-bits or less).  For larger numbers
  90. ' the Rabin-Miller test should be used.
  91. '
  92. Public Function IsPrime(ByVal n As Long) As Boolean
  93.     Dim i As Long
  94.  
  95.     IsPrime = False
  96.     
  97.     If n <> 2 And (n And 1) = 0 Then Exit Function 'test if div 2
  98.     If n <> 3 And n Mod 3 = 0 Then Exit Function 'test if div 3
  99.     For i = 6 To Sqr(n) Step 6
  100.         If n Mod (i - 1) = 0 Then Exit Function
  101.         If n Mod (i + 1) = 0 Then Exit Function
  102.     Next
  103.     
  104.     IsPrime = True
  105. End Function
  106.