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. It is not present when compiling for the Unity test runner.

 1/*
 2Project Euler Problem 19
 3
 4This one ended up being very easy thanks to the time 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 <stdio.h>
27#include <stdint.h>
28#include <inttypes.h>
29#include "include/macros.h"
30
31#ifdef _WIN32
32#include <string.h>
33#include <windows.h>
34#else
35#include <time.h>
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    struct tm date = {0};
47#endif
48
49    for (int year = 1901; year <= 2000; ++year) {
50        for (int month = 0; month < 12; ++month) {
51#ifdef _WIN32
52            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                return -1;
59            if (!FileTimeToSystemTime(&fileTime, &normalizedTime))
60                return -1;
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 (mktime(&date) == -1) {
70                fprintf(stderr, "mktime failed to normalize the date.\n");
71                return -1;
72            }
73
74            if (date.tm_wday == 0)
75                ++answer;
76#endif
77        }
78    }
79    return answer;
80}
81
82
83PROGRAM_TAIL("%" PRIu16, p0019)
84#endif

Tags: calendar, combinatorics