Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
big factorial
#1
just for fun
Code: (Select All)
$Console:Only
_Dest _Console
Option _Explicit

Dim As Long d, i, n, dm
Dim As Double t
Const big_base = 1000000000~&&

n = 1
While n > 0
    Input "n "; n
    If n = 0 Then End
    ' calculate the number of decimal digits of the factorial using the Strling approximation
    d = (.2171472409516259# + .4342944819032518 * n) * Log(n) + .3990899341790576# - .4342944819032518# * n
    dm = d \ 9 'divide the number of digits by 9 to get the maximum array dimension

    ReDim As _Unsigned Long fac(dm)
    Dim As String s, sf

    t = Timer(.0001)
    fac(0) = 1 ' start with 1

    For i = 2 To n
        a_mul fac(), i
    Next
    t = Timer(.0001) - t

    ' convert the array to string
    sf = ""
    For i = 0 To dm
        s = _Trim$(Str$(fac(i)))
        If Len(s) < 9 Then
            s = String$(9 - Len(s), "0") + s
        End If
        sf = s + sf
    Next
    'strip leading 0's
    While Left$(sf, 1) = "0"
        sf = Mid$(sf, 2)
    Wend

    Print sf
    Print "elapsed time "; t; " seconds"
Wend

Sub a_mul (arr1() As _Unsigned Long, m As _Unsigned _Integer64)
    Static As Long nlimbs ' start with 1 number of elements (nlimbs = 0)
    Dim As Long carry, i
    Dim As _Unsigned _Integer64 tmp
    carry = 0
    For i = 0 To nlimbs
        tmp = m * arr1(i) + carry
        carry = tmp \ big_base
        arr1(i) = tmp Mod big_base
    Next
    If carry > 0 Then
        nlimbs = nlimbs + 1 ' increment the number of elements
        arr1(nlimbs) = carry
    End If
End Sub
Reply
#2
Thumbs Up 
Wow I just 20,000 fast!!!! very impressive fun Smile
b = b + ...
Reply
#3
It's so fast it almost takes off. I once tried to display size and time graphically in Julia, it should be quite easy; see screenshot (example from the manual). But it remained with the attempt. I did not understand how this works.

[Image: Julia-Plots2023-04-21.jpg]
Reply




Users browsing this thread: 1 Guest(s)