C Implementation of Problem 20

View source code here on GitHub!

Includes

Solution

uint64_t p0020()
int main(int argc, char const *argv[])

Note

This function is only present in the Python test runner, or when compiling as a standalone program. It is not present when compiling for the Unity test runner.

 1/*
 2Project Euler Problem 20
 3
 4Problem:
 5
 6n! means n × (n − 1) × ... × 3 × 2 × 1
 7
 8For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
 9and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
10
11Find the sum of the digits in the number 100!
12*/
13#ifndef EULER_P0020
14#define EULER_P0020
15#include <stdint.h>
16#include <inttypes.h>
17#include <stdio.h>
18#include "include/macros.h"
19
20uint64_t EMSCRIPTEN_KEEPALIVE p0020() {
21    uint64_t numbers[10] = {};
22    const uint64_t ten17 = 100000000000000000;
23    numbers[0] = 1;
24    for (uint8_t i = 2; i <= 100; i++) {
25        for (uint8_t j = 0; j < 10; j++)
26            numbers[j] *= i;
27        for (uint8_t j = 0; j < 9; j++)
28            if (numbers[j] > ten17) {
29                numbers[j + 1] += numbers[j] / ten17;
30                numbers[j] %= ten17;
31            }
32    }
33    uint64_t answer = 0;
34    uint64_t power = 1;
35    while (power < ten17) {
36        for (uint8_t j = 0; j < 10; j++)
37            answer += (numbers[j] / power) % 10;
38        power *= 10;
39    }
40    return answer;
41}
42
43PROGRAM_TAIL("%" PRIu64, p0020)
44#endif

Tags: large-numbers, digit-sum, factorial