方法一: program mainimplicit nonereal*8 :: Rfact100integer,allocatable :: main_digits(:),sub_digits(:,:)integer :: num_digitsinteger :: i,j!先用双精度数算出100!,有效位数只有15位Rfact100=1.0d0do i=1,100 Rfact100=Rfact100*dble(i)end do!求得100阶乘有多少位数字,包括低位上的0num_digits=dlog10(Rfact100)+1!分配一个数组,数组每个元素代表一个数字allocate(main_digits(num_digits),sub_digits(num_digits,3))!赋初值main_digits=0main_digits(1)=1do i=2,100 !每一位数字都乘以i,每个数都不会超过900,所以最多3位数字 main_digits=main_digits*i !分解每位数,进位处理 do j=1,num_digits call int2digits(main_digits(j),sub_digits(j,:)) if(j<=num_digits-2) then main_digits(j)=sub_digits(j,1) main_digits(j+1)=main_digits(j+1)+sub_digits(j,2) main_digits(j+2)=main_digits(j+2)+sub_digits(j,3) else if(j==num_digits-1) then main_digits(j)=sub_digits(j,1) main_digits(j+1)=main_digits(j+1)+sub_digits(j,2) else main_digits(j)=sub_digits(j,1) end if end do end dowrite(*,*) '100!='!输出从左到右输出do i=num_digits,1,-1 write(*,fmt='(I1)',advance='no') main_digits(i)end dowrite(*,*)deallocate(main_digits,sub_digits)pauseend program main!把整数分解成数字subroutine int2digits(int,digit)integer,intent(in) :: intinteger,intent(out) :: digit(3)integer :: int_tempinteger :: iint_temp=intdo i=1,3 digit(i)=mod(int_temp,10) int_temp=int_temp/10end doend subroutine int2digits100!=93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 This method can be easily modified to calculate the factorial for 10000, and the computatonal time is about 80 seconds. Method 2: use big_integer module !The code is listed as follows Before using the module, the parameter nr_of_decimal_digits should be set big enough so that all the digits can be accomodated in the big_integer type. integer, parameter, public :: nr_of_decimal_digits = 40000program mainuse big_integer_moduletype(big_integer) :: fact100integer :: ireal*8 :: time_begin,time_endcall cpu_time(time_begin)fact100=1do i=1,10000 fact100=fact100*iend docall cpu_time(time_end)call print_big(fact100)write(*,*) 'computatonal time=',time_end-time_begin,'seconds'write(*,*) 'number of digits=',len_trim(char(fact100))pauseend program main computatonal time= 0.998406400000000 second number of digits= 35660As we can see, the big_integer module is of high efficiency.

评论