C++ Implementation of Problem 34

View source code here on GitHub!

Includes

Solution

uint64_t p0034()
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.

 1/*
 2Project Euler Problem 34
 3
 4Problem:
 5
 6145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
 7
 8Find the sum of all numbers which are equal to the sum of the factorial of
 9their digits.
10
11Note: as 1! = 1 and 2! = 2 are not sums they are not included.
12*/
13#ifndef EULER_P0034
14#define EULER_P0034
15#include <stdint.h>
16#include <iostream>
17#include <cstdio>
18#include "include/macros.hpp"
19#include "include/math.hpp"
20
21uint64_t EMSCRIPTEN_KEEPALIVE p0034() {
22    uint64_t answer = 0, sum;
23    for (uint64_t i = 10; i < 100000; i++) {
24        sum = 0;
25        char buf[8] = {};
26        // I know snprintf exists, but it isn't defined in C++98,
27        // and this isn't taking in user input
28        sprintf(buf, "%" PRIu64, i);
29        for (uint8_t j = 0; j < 8 && buf[j]; j++)
30            sum += factorial(buf[j] - '0');
31        if (sum == i)
32            answer += i;
33    }
34    return answer;
35}
36
37PROGRAM_TAIL(p0034)
38#endif

Tags: factorial, digit-sum