C++ Implementation of Problem 19
View source code here on GitHub!
Includes
Solution
-
uint16_t p0019()
-
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 19
3
4This one ended up being very easy thanks to the ctime library
5
6Problem:
7
8You are given the following information, but you may prefer to do some research
9for yourself.
10
11 1 Jan 1900 was a Monday.
12 Thirty days has September,
13 April, June and November.
14 All the rest have thirty-one,
15 Saving February alone,
16 Which has twenty-eight, rain or shine.
17 And on leap years, twenty-nine.
18 A leap year occurs on any year evenly divisible by 4, but not on a century
19 unless it is divisible by 400.
20
21How many Sundays fell on the first of the month during the twentieth century
22(1 Jan 1901 to 31 Dec 2000)?
23*/
24#ifndef EULER_P0019
25#define EULER_P0019
26#include <iostream>
27#include <stdexcept>
28#include <stdint.h>
29#include "include/macros.hpp"
30
31#ifdef _WIN32
32#include <cstring>
33#include <windows.h>
34#else
35#include <ctime>
36#endif
37
38uint16_t EMSCRIPTEN_KEEPALIVE p0019() {
39 uint16_t answer = 0;
40
41#ifdef _WIN32
42 SYSTEMTIME systemTime;
43 FILETIME fileTime;
44 SYSTEMTIME normalizedTime;
45#else
46 std::tm date = {0};
47#endif
48
49 for (int year = 1901; year <= 2000; ++year) {
50 for (int month = 0; month <= 11; ++month) {
51#ifdef _WIN32
52 std::memset(&systemTime, 0, sizeof(systemTime));
53 systemTime.wYear = year;
54 systemTime.wMonth = month + 1;
55 systemTime.wDay = 1;
56
57 if (!SystemTimeToFileTime(&systemTime, &fileTime))
58 throw std::runtime_error("SystemTimeToFileTime failed.");
59 if (!FileTimeToSystemTime(&fileTime, &normalizedTime))
60 throw std::runtime_error("FileTimeToSystemTime failed.");
61
62 if (normalizedTime.wDayOfWeek == 0)
63 ++answer;
64#else
65 date.tm_year = year - 1900;
66 date.tm_mon = month;
67 date.tm_mday = 1;
68
69 if (std::mktime(&date) == -1)
70 throw std::runtime_error("mktime failed to normalize the date.");
71 if (date.tm_wday == 0)
72 ++answer;
73#endif
74 }
75 }
76 return answer;
77}
78
79
80PROGRAM_TAIL(p0019)
81#endif