C++ Implementation of Problem 22
View source code here on GitHub!
Includes
<iostream>
(implicitly, via utils.hpp)<cerrno>
(implicitly, via utils.hpp)<iostream>
(implicitly, via utils.hpp)<stdexcept>
(implicitly, via utils.hpp)<inttypes.h>
(implicitly, via utils.hpp)<cstring>
(implicitly, via utils.hpp)<string>
(implicitly, via utils.hpp)<sstream>
(implicitly, via utils.hpp)<fstream>
(implicitly, via utils.hpp)<windows.h> (implicitly, via utils.hpp & if compiled for Windows)
<libgen.h> (implicitly, via utils.hpp & if not compiled for Windows)
<libgen.h> (implicitly, via utils.hpp & if not compiled for Windows)
Solution
-
uint64_t p0022()
-
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/**
2 * Project Euler Problem 22
3 *
4 * I know that this could be done faster with a traditional for loop, but I wanted
5 * to see if iterators were reasonably possible in C, since it makes the prime
6 * number infrastructure a lot easier to set up.
7 *
8 * Problem:
9 *
10 * If we list all the natural numbers below 10 that are multiples of 3 or 5, we
11 * get 3, 5, 6 and 9. The sum of these multiples is 23.
12 *
13 * Find the sum of all the multiples of 3 or 5 below 1000.
14 */
15#ifndef EULER_P0022
16#define EULER_P0022
17#include <stdint.h>
18#include <iostream>
19#include <vector>
20#include <algorithm>
21#include "include/macros.hpp"
22#include "include/utils.hpp"
23
24uint64_t EMSCRIPTEN_KEEPALIVE p0022() {
25 uint64_t answer = 0;
26 std::string fstring = get_data_file("p0022_names.txt");
27 const uint32_t name_count = 5163;
28 std::vector<std::string> names(5163, "");
29 size_t idx = 0, i = 0, pi = 0;
30 do {
31 while (i < fstring.length() && fstring[i] != ',')
32 i++;
33 const size_t len = i - pi - 2;
34 names[idx++] = fstring.substr(pi + 1, len);
35 pi = ++i;
36 } while (i < fstring.length());
37 std::sort(names.begin(), names.end());
38 for (idx = 0; idx < name_count; idx++) {
39 uint64_t score = 0;
40 for (i = 0; names[idx][i]; i++)
41 score += names[idx][i] & 0x3F;
42 answer += score * (idx + 1);
43 }
44 return answer;
45}
46
47PROGRAM_TAIL(p0022)
48#endif