计算大数阶乘--VB Script 版

和Basic版相比,这个版本有以下几处不同点
这次采用的不是静态数组,而是动态数组,先定义一个数组“Dim buff()”,在运行过程中再根据需要扩展大小。
计算结果没有直接输出,而是写到文件,因为当字符串太长时,MsgBox的会丢失部分内容
难点:确定n!的位数是难点,ln(n!) 可用 斯特林逼近 来计算,ln(n!)= (n+0.5)ln(n)- n + 0.5*ln(2*pi)
请参考 http://mathworld.wolfram.com/StirlingsApproximation.html

下面为源代码

Dim n,i,j,c,t,len1
Dim buff()
Dim numstr

Const RAD=10000
Const PI=3.1415926535897932384626433832795

numstr= InputBox( "please input a numer n(n>1)", "calculate the n!", 1)

if  numstr > "" and IsNumeric( numstr ) Then
   
    n=CLng(numstr)
    log_facn=(n+0.5)*Log(n)-n+0.5*Log(2*PI) 'log_facn=ln(n!)
    ReDim buff(log_facn/Log(RAD)+1)         'Expand array size for store n!
        
    buff(1)=1
    len1=1
    
    For i=1 to n
        c=CLng(0)
        For j= 1 to len1
           t=CLng(buff(j))* CLng(i)+c
           buff(j)=t MOD RAD
           c=t \ RAD
        Next
        
        If c>0 Then
            len1=len1+1
            buff(len1)=c    
        End If    
    Next
   
    'Caculation is completed, the following code for write the result to file
    filename=".\" & CStr(n) & ".txt"
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set a = fs.CreateTextFile(filename, True)
    
    numstr=CStr(buff(len1))
    For j=len1-1 to 1 step -1
        t=CStr(buff(j))
        If Len(t)<4 Then
            numstr=numstr & String(4-Len(t),"0")    
        End If
        numstr=numstr & t
        If Len(numstr) > 76 Then
            a.WriteLine(numstr)
            numstr=""
        End if    
    Next
    If (Len(numstr)>0) Then
        a.WriteLine(numstr)
    End If
    a.close
             
    MsgBox "Result have been stored to file " & filename,0,"calculate n!"
Else
    MsgBox "Invalid input" 
End if


参考学习资料
1. VBScript 教程,可从VBScript http://download.pchome.net/development/reference/detail-11108.html
2. VB script 脚本语言.doc

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值