Skip to content

Instantly share code, notes, and snippets.

@honda0510
Last active December 14, 2015 17:09
Show Gist options
  • Save honda0510/5120501 to your computer and use it in GitHub Desktop.
Save honda0510/5120501 to your computer and use it in GitHub Desktop.
商、剰余、べき乗 | ~ 車輪の再発明シリーズ ~ http://www.moug.net/faq/viewtopic.php?t=65743
Option Explicit
Function Quotient(ByVal Dividend, ByVal Divisor) As Variant
'Quotient = Dividend \ Divisor
Quotient = Fix(Dividend / Divisor)
End Function
Function Modular(ByVal Dividend, ByVal Divisor) As Variant
'Modular = Dividend Mod Divisor
Modular = Dividend - Quotient(Dividend, Divisor) * Divisor
End Function
Option Explicit
Function Power(ByVal Base As Long, ByVal Exponent As Long)
If Exponent < 0 Then
Err.Raise 5
End If
Power = Power_(CDec(Base), Exponent)
End Function
Private Function Power_(ByVal Base, ByVal Exponent As Long)
'Power = Base ^ Exponent
Static Memo As New Collection
Dim Params As String
Dim Visited As Boolean
Dim Sum As Variant
Params = Base & "^" & Exponent
On Error Resume Next
Power_ = Memo.Item(Params)
Visited = Err.Number = 0
On Error GoTo 0
If Visited Then Exit Function
If Exponent = 0 Then
Sum = 1
Else
Sum = Base * Power_(Base, Exponent - 1)
End If
Power_ = Sum
Memo.Add Sum, Params
End Function
Option Explicit
Function Power(ByVal Base As Long, ByVal Exponent As Long)
'Power = Base ^ Exponent
Dim Sum As Variant
Dim n As Long
Dim i As Long
If Exponent = 0 Then
Sum = 1
Else
Sum = CDec(Base)
n = Exponent - 1
For i = 1 To n
Sum = Sum * Base
Next i
End If
Power = Sum
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment