AutoHotkey Community

It is currently May 27th, 2012, 10:22 am

All times are UTC [ DST ]




Post new topic Reply to topic  [ 18 posts ]  Go to page Previous  1, 2
Author Message
 Post subject:
PostPosted: May 29th, 2009, 7:05 am 
Offline

Joined: November 4th, 2008, 9:23 am
Posts: 1045
Thanks. Wow... that's real fast!

Code:
#SingleInstance Force
MP_Init()

start := A_TickCount
result := factoral(1000)

;took 100ms - 125ms, for me
MsgBox, % "It took " (A_TickCount - start) " ms."

MsgBox, % result

factoral(n)
{
    MP_set(result, 1)

    Loop, %n%
    {
        MP_set(tmpVal, A_Index)

        MP_mul(tmpResult, result, tmpVal)
        MP_cpy(result, tmpResult)
    }

    return MP_dec(result)
}

_________________
As always, if you have any further questions, don't hesitate to ask.

Add OOP to your scripts via the Class Library. Check out my scripts.


Report this post
Top
 Profile  
Reply with quote  
 Post subject:
PostPosted: May 29th, 2009, 6:05 pm 
Offline

Joined: February 14th, 2005, 4:05 pm
Posts: 4710
Location: Boulder, CO
You can multiply with short integers, saving MP_Set calls. This could be the shortest code:
Code:
factorial(n) {
    MP_Set(result, 1)
    Loop %n%
        MP_MulIpp(tmpVal, result, A_Index)
       ,MP_Cpy(result, tmpVal)
    Return MP_Dec(result)
}
You can also avoid copying long integers with a little longer function, which is, therefore, a little faster:
Code:
factorial(n) { ; n >= 0
    If n < 4
       Return SubStr("1261",n,1)
    MP_Set(x,n), i := n
    Loop % n//2-2
        MP_MulIpp(y,x,--i)
       ,MP_MulIpp(x,y,--i)
    MP_MulIpp(y, x, i=4 ? 6 : 24)
    Return MP_Dec(y)
}

You can handle more than just the 4 possible smallest inputs directly. E.g. if the factorials of n<10 are directly returned, the loop can finish sooner and the last MP_MulIpp can have choices between 9! or 10!, resulting in further little speedups.


Report this post
Top
 Profile  
Reply with quote  
 Post subject:
PostPosted: June 13th, 2010, 2:21 pm 
Offline

Joined: February 14th, 2005, 4:05 pm
Posts: 4710
Location: Boulder, CO
I created a directory in AutoHotkey.net for the Multi-precision integer library and related functions. The library has to be included, before the long integer functions are used. (It contains a call to the initialization function.)

Some tests and example code is included in a test script.

The C source code of the machine code routines is also uploaded for reference.


Report this post
Top
 Profile  
Reply with quote  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 18 posts ]  Go to page Previous  1, 2

All times are UTC [ DST ]


Who is online

Users browsing this forum: XX0 and 26 guests


You can post new topics in this forum
You can reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Search for:
Powered by phpBB® Forum Software © phpBB Group