|
1 | | -! In program name, - is not allowed |
2 | | -!works till 77 |
3 | | -! 78 and above is out of the reasonable bounds for calculation |
4 | | -program factorial_generate |
5 | | - character(len=10) :: argument |
6 | | - Character(26) :: low = 'abcdefghijklmnopqrstuvwxyz' |
7 | | - Character(26) :: cap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' |
8 | | - integer :: number, check_capital_letters, check_small_letters, i |
9 | | - integer(kind = 16):: factorial |
10 | | - ! Anything not equal to single argument, Print Error |
11 | | - IF(COMMAND_ARGUMENT_COUNT().NE.1)THEN |
12 | | - write(*,'(g0.8)')"Usage: please input a non-negative integer" |
13 | | - STOP |
14 | | - ENDIF |
15 | | - |
16 | | - CALL GET_COMMAND_ARGUMENT(1,argument) |
17 | | - if (argument == "") then |
18 | | - write(*,'(g0.8)')"Usage: please input a non-negative integer" |
19 | | - STOP |
20 | | - endif |
21 | | - ! Scan for letters |
22 | | - check_capital_letters = scan(argument, cap) |
23 | | - check_small_letters = scan(argument, low) |
24 | | - ! If capital letters exist, print error |
25 | | - if (check_capital_letters > 0) then |
26 | | - write(*,'(g0.8)')"Usage: please input a non-negative integer" |
27 | | - STOP |
28 | | - endif |
29 | | - ! If small letters exist, print error |
30 | | - if (check_small_letters > 0) then |
31 | | - write(*,'(g0.8)')"Usage: please input a non-negative integer" |
32 | | - STOP |
33 | | - endif |
34 | | - ! read the cmd line arg into number |
35 | | - read (argument, '(I10)') number |
36 | | - |
37 | | - if (number < 0) then |
38 | | - write(*,'(g0.8)')"Usage: please input a non-negative integer" |
39 | | - STOP |
40 | | - endif |
41 | | - if (number > 77) then |
42 | | - write(*,'(g0.8)')"Input is out of the reasonable bounds for calculation" |
43 | | - STOP |
44 | | - endif |
45 | | - |
46 | | - factorial = 1 |
47 | | - do i = 1, number |
48 | | - factorial = factorial * i |
49 | | - end do |
50 | | - write(*,'(g0.8)') factorial |
51 | | -end program |
| 1 | +program factorial |
| 2 | + use, intrinsic :: iso_fortran_env, only: int64 |
| 3 | + implicit none |
| 4 | + |
| 5 | + character(len=64) :: arg |
| 6 | + integer :: ios |
| 7 | + integer(kind=int64) :: n, i |
| 8 | + |
| 9 | + if (command_argument_count() /= 1) call usage() |
| 10 | + |
| 11 | + call get_command_argument(1, arg) |
| 12 | + arg = adjustl(trim(arg)) |
| 13 | + if (len_trim(arg) == 0) call usage() |
| 14 | + |
| 15 | + read(arg, *, iostat=ios) n |
| 16 | + if (ios /= 0 .or. n < 0_int64) call usage() |
| 17 | + |
| 18 | + write(*,'(i0)') product((/(i, i = 1_int64, n)/)) |
| 19 | + |
| 20 | +contains |
| 21 | + |
| 22 | + subroutine usage() |
| 23 | + write(*,'(a)') "Usage: please input a non-negative integer" |
| 24 | + stop |
| 25 | + end subroutine usage |
| 26 | + |
| 27 | +end program factorial |
0 commit comments