-
Notifications
You must be signed in to change notification settings - Fork 0
/
binomials.f90
61 lines (42 loc) · 1.4 KB
/
binomials.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
58
59
60
61
! This program computes tables of binomial coefficients for values of k from 0 to n
PROGRAM binomial
IMPLICIT NONE
! Variables are declared
INTEGER::binom, k=0, n, binomial_coeff, n_factorial, factorial
CHARACTER::str
! User input is provided via command line argument
call GET_COMMAND_ARGUMENT(1,str)
n = nint(real(str))
write (*, '(a," ", a)') "k", "n!/(k!(n-k)!)"
write (*, '(a)') "======================"
do k = 0, n
! For each value of k, the binomial coefficient is calculated
binom = binomial_coeff(n, k)
write (*, '(i6," ",i8)') k, binom
end do
END PROGRAM binomial
! Function that takes 2 integer arguments, n and k, and returns the value of the binomial coefficient
FUNCTION binomial_coeff(n, k) result(binom)
IMPLICIT NONE
INTEGER::n, k, s, binom, denom, n_factorial
s = n - k
binom = n_factorial(n) / n_factorial(k) * n_factorial(s)
END FUNCTION
! Function that takes an integer argument, n, and returns n!
FUNCTION n_factorial(n) result(n_fact)
IMPLICIT NONE
INTEGER, INTENT(IN)::n
INTEGER:: n_fact, factorial
n_fact = factorial(n)
END FUNCTION
! Function for calculating the factorials
FUNCTION factorial(inp) result(y)
IMPLICIT NONE
INTEGER, INTENT(IN)::inp
INTEGER:: y, nth_fact=1, n_count=1
DO WHILE (n_count <= inp)
nth_fact = nth_fact * n_count
n_count = n_count + 1
END DO
y = nth_fact
END FUNCTION factorial