RosettaCodeData/Task/Juggler-sequence/FreeBASIC/juggler-sequence.basic
2025-06-11 20:16:52 -04:00

87 lines
1.8 KiB
Text

#include "big_int/big_integer.bi"
Type JugglerResult
length As Integer ' Sequence length
maxVal As BigInt ' Maximum value
maxIdx As Integer ' Index where maximum occurs
End Type
Function BigIntSqrt(Byref n As BigInt) As BigInt
If n = 0 Then Return 0
Dim As BigInt x = n
Dim As BigInt y = (x + 1) \ 2
While y < x
x = y
y = (x + n \ x) \ 2
Wend
Return x
End Function
Function BigIntToStr(Byref n As BigInt) As String
If n = 0 Then Return "0"
Dim As String result
Dim As BigInt tmp = n
Dim As BigInt ten = 10
Dim As BigInt digit
While tmp <> 0
digit = tmp Mod 10
result = Chr(Cint(digit) + Asc("0")) & result
tmp \= 10
Wend
Return result
End Function
Function Juggler(n As Uinteger) As JugglerResult
Dim As JugglerResult result
Dim As BigInt a = n
result.length = 0
result.maxVal = a
result.maxIdx = 0
While a <> 1
If (a Mod 2) = 0 Then
' Even: floor(sqrt(a))
a = BigIntSqrt(a)
Else
' Odd: floor(a^(3/2)) = floor(sqrt(a³))
Dim As BigInt a_cubed = a * a * a
a = BigIntSqrt(a_cubed)
End If
result.length += 1
If a > result.maxVal Then
result.maxVal = a
result.maxIdx = result.length
End If
Wend
Return result
End Function
' Main program
Print "n l[n] h[n] i[n]"
Print String(31, "-")
For n As Integer = 20 To 39
Dim As JugglerResult result = Juggler(n)
Dim As String maxValStr = BigIntToStr(result.maxVal)
Print Using "## ## "; n; result.length;
If Len(maxValStr) < 14 Then
Print Space(14 - Len(maxValStr)); maxValStr;
Else
Print maxValStr;
End If
Print Using " ##"; result.maxIdx
Next
Sleep