Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a number has an integer cubic root

Tags:

vba

I am trying to check whether a given number is cuberoot or not in VBA.
The following code works only for 2 and 3 as answers, it does not work after that.
I am trying to figure out what is wrong in the code.

Sub cuberoot()
    Dim n As Long, p As Long, x As Long, y As Long

    x = InputBox("x= ")
    If Iscube(x) Then
        MsgBox ("Is cube")
    Else
        MsgBox ("No cube")
    End If
End Sub

Private Function Iscube(a As Long) As Boolean
    b = a ^ (1 / 3)
    If b = Int(b) Then
        Iscube = True
    Else
        Iscube = False
    End If
End Function
like image 825
Apurva Avatar asked Oct 20 '22 13:10

Apurva


1 Answers

Since you are passing in a Long I'll assume that you won't have a number bigger than roughly 2*10^9 so this should always work. It's a slight variation where you truncate the double and then compare to the two nearest integers to make sure you catch any rounding errors.

Edit: In VBA the truncating would always round so it's only neccessary to check the 3rd root value:

Public Function Iscube(a As Long) As Boolean

Dim b As Integer
b = CInt(a ^ (1# / 3#))

If (b ^ 3 = a) Then
    Iscube = True
Else
    Iscube = False
End If

End Function

If you need a number larger than a Long you'll need to change your input type and you might want to consider an iterative method like a binary search or a Newton-Raphson solver instead.

like image 176
stucharo Avatar answered Nov 15 '22 06:11

stucharo