/
fact-m.f90
57 lines (44 loc) · 2 KB
/
fact-m.f90
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
! --------------------------------------------------------------------
! MODULE FactorialModule
! This module contains two procedures: Factorial(n) and
! Combinatorial(n,r). The first computes the factorial of an integer
! n and the second computes the combinatorial coefficient of two
! integers n and r.
! --------------------------------------------------------------------
MODULE FactorialModule
IMPLICIT NONE
CONTAINS
! --------------------------------------------------------------------
! FUNCTION Factorial() :
! This function accepts a non-negative integers and returns its
! Factorial.
! --------------------------------------------------------------------
INTEGER (selected_int_kind(30)) FUNCTION Factorial(n)
IMPLICIT NONE
INTEGER , INTENT(IN) :: n ! the argument
INTEGER (selected_int_kind(30)) :: Fact, i ! result
Fact = 1 ! initially, n!=1
DO i = 1, n ! this loop multiplies
Fact = Fact * i ! i to n!
END DO
Factorial = Fact
END FUNCTION Factorial
! --------------------------------------------------------------------
! FUNCTION Combinarotial():
! This function computes the combinatorial coefficient C(n,r).
! If 0 <= r <= n, this function returns C(n,r), which is computed as
! C(n,r) = n!/(r!*(n-r)!). Otherwise, it returns 0, indicating an
! error has occurred.
! --------------------------------------------------------------------
INTEGER (selected_int_kind(30)) FUNCTION Combinatorial(n, r)
IMPLICIT NONE
INTEGER, INTENT(IN) :: n, r
INTEGER (selected_int_kind(30)) :: Cnr
IF (0 <= r .AND. r <= n) THEN ! valid arguments ?
Cnr = Factorial(n) / Factorial(r) / Factorial(n-r)
ELSE ! no,
Cnr = 0 ! zero is returned
END IF
Combinatorial = Cnr
END FUNCTION Combinatorial
END MODULE FactorialModule