On 2002-10-26 12:42, Charlie wrote:
How would I go about coding an app to work out how many iterations it would take to reduce a user entered number to one.
Im looking to divide the number by / 2 if the number is even.
If the number is odd im looking to use * 3 + 1.
Can somebody give me a clue on how I would go about this please.
Charlie
Here are a couple of ways to do it. The first one prompts the user for the number and then tells them the number of iterations. The second one uses recursion and can be used as a worksheet formula. You can call it like this:
=NUMITER2(33)
Of course, you can also change the first one to be a worksheet function if you like.
<pre><font color='#000000'>
<font color='#000080'>Sub</font> NumIterations()
<font color='#000080'>Dim</font> lngNum <font color='#000080'>As</font> <font color='#000080'>Long</font>
<font color='#000080'>Dim</font> lngIterations <font color='#000080'>As</font> <font color='#000080'>Long</font>
lngNum = Application.InputBox(Prompt:="Please enter a number", _
Title:="My Title", Type:=1)
<font color='#000080'>Do</font> <font color='#000080'>While</font> lngNum > 1
<font color='#000080'>If</font> (lngNum And 1) = 1 <font color='#000080'>Then</font>
lngNum = (lngNum * 3) + 1
<font color='#000080'>Else</font>
lngNum = lngNum / 2
<font color='#000080'>End</font> <font color='#000080'>If</font>
lngIterations = lngIterations + 1
<font color='#000080'>Loop</font>
MsgBox "The number you entered took " & lngIterations & _
" iterations to get to 1."
<font color='#000080'>End</font> <font color='#000080'>Sub</font>
<font color='#000080'>Function</font> NumIter2(lngNum <font color='#000080'>As</font> Long) <font color='#000080'>As</font> <font color='#000080'>Long</font>
<font color='#000080'>If</font> (lngNum And 1) = 1 <font color='#000080'>Then</font>
lngNum = (lngNum * 3) + 1
<font color='#000080'>Else</font>
lngNum = lngNum / 2
<font color='#000080'>End</font> <font color='#000080'>If</font>
<font color='#000080'>If</font> lngNum = 1 <font color='#000080'>Then</font>
NumIter2 = 1
<font color='#000080'>Else</font>
NumIter2 = NumIter2(lngNum) + 1
<font color='#000080'>End</font> <font color='#000080'>If</font>
<font color='#000080'>End</font> <font color='#000080'>Function</font>
</font></pre>
Hope this helps,
Russell