Factorials, Factors and Multiples
Public Function Factoral(n As Integer) As Double
If n < 1 OrElse n > 170 Then Return 0
' Factoral of 171 is larger than Double.maxvalue
Dim ret As Double = 1
For i As Integer = 1 To n
ret *= i
Next
Return ret
End Function
'
Private Function Factorize(n As Integer) As List(Of Integer)
' Prime numbers will return an empty list
' List never includes 1 or the number
' This works for numbers between +2 and Integer.MaxValue (+2,147,483,647)
' However, this method is not suitable for testing huge numbers.
Dim listFactors As New List(Of Integer)
Dim sqrtOfN As Integer = CInt(Math.Ceiling(Math.Sqrt(n)))
While n Mod 2 = 0
n \= 2
listFactors.Add(2)
End While
For i As Integer = 3 To sqrtOfN Step 2
While n Mod i = 0
n \= i
listFactors.Add(i)
End While
If i > n OrElse i > sqrtOfN Then
Exit For
End If
Next
Return listFactors
End Function
'
Private Shared Function GreatestCommonFactor(a As Integer, b As Integer) As Integer
Dim temp As Integer
While b <> 0
temp = b
b = a Mod b
a = temp
End While
Return a
End Function
'
Private Function LowestCommonMultiple(a As Integer, b As Integer) As Integer
Dim temp, a1, b1 As Integer
a1 = a
b1 = b
While b1 <> 0
temp = b1
b1 = a1 Mod b1
a1 = temp
End While
Return a * b \ a1
End Function
Permutations
Public Function Permutation(num1 As Integer, num2 As Integer) As Long
Dim temp As Integer = num1
Dim ret As Long = 1
If num1 > num2 Then
num1 = num2
num2 = temp
End If
If num1 < 1 OrElse num2 < 1 Then Return 0
For i As Integer = num1 To num2
ret *= i
Next
Return ret
End Function
'
Private Function IsPrime(n As Integer) As Boolean
' This works for numbers between +2 and Integer.MaxValue (+2,147,483,647)
' There is mathematical debate as to whether 0 and 1 are Prime Numbers
' This method is not suitable for testing huge numbers.
If n < 3 Then Return True
If n Mod 2 = 0 Then Return False
Dim primeNumber As Boolean = True
For i = 3 To Math.Floor(Math.Sqrt(n)) Step 2
If n Mod i = 0 Then
primeNumber = False
Exit For
End If
Next
Return primeNumber
End Function
'
Private Function ListAllPrimes(max As Integer) As List(Of Integer)
' note - large values for max (> about 10000) will need to be run in background to avoid risk of timeout errors
' very large values for max (> about 1000000) may not complete in a realistic timescale!
Dim ret As New List(Of Integer)
Dim prime As Boolean
For i As Integer = 3 To max Step 2
prime = True
For Each p As Integer In ret
If i Mod p = 0 Then
prime = False
Exit For
End If
Next
If prime Then
ret.Add(i)
End If
Next
If max >= 2 Then ret.Insert(0, 2)
Return ret
End Function
Combinations
Public Function Combination(num1 As Integer, num2 As Integer) As Long
Dim temp As Integer = num1
If num1 > num2 Then
num1 = num2
num2 = temp
End If
If num1 < 1 OrElse num2 < 1 Then Return 0
Return Factoral(num2) / (Factoral(num1) * Factoral(num2 - num1))
End Function
DigitalDan.co.uk