Fortran Implementation of Problem 20

View source code here on GitHub!

Includes

Problem Solution

integer Problem0020/p0020()
 1! Project Euler Problem 20
 2!
 3! Problem:
 4!
 5! n! means n × (n − 1) × ... × 3 × 2 × 1
 6!
 7! For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
 8! and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
 9!
10! Find the sum of the digits in the number 100!
11
12module Problem0020
13    use constants
14    implicit none
15contains
16    pure integer(i18t) function p0020() result(answer)
17        integer(i18t), dimension(10) :: numbers
18        integer(i18t) :: power
19        integer :: i, j
20        
21        power = 1
22        answer = 0
23        numbers = 0
24        numbers(1) = 1
25        do i = 2, 100
26            do j = 1, size(numbers)
27                numbers(j) = numbers(j) * i
28            end do
29            do j = 1, size(numbers) - 1
30                if (numbers(j) > ten16) then
31                    numbers(j + 1) = numbers(j + 1) + numbers(j) / ten16
32                    numbers(j) = mod(numbers(j), ten16)
33                end if
34            end do
35        end do
36        do i = 1, 18
37            do j = 1, size(numbers)
38                answer = answer + mod((numbers(j) / power) , 10_i18t)
39            end do
40            power = power * 10
41        end do
42    end function p0020
43end module Problem0020

Tags: large-numbers, digit-sum, factorial