Skip to content

Instantly share code, notes, and snippets.

@kotarot
Last active August 13, 2020 11:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kotarot/1b2aeb32e3a7ab444e29ee3c78ed0fd0 to your computer and use it in GitHub Desktop.
Save kotarot/1b2aeb32e3a7ab444e29ee3c78ed0fd0 to your computer and use it in GitHub Desktop.
birthday.c -- for lecture
#include <stdio.h>
#include <stdlib.h>
// Returns 1 if the given date exists, 0 if not.
// Ref: Leap year https://ja.wikipedia.org/wiki/%E9%96%8F%E5%B9%B4
int is_correct_day(int y, int m, int d) {
if (m == 2) {
if (d > 29) { // d = 30,31 is incorrect
return 0;
} else if (d == 29) {
if (y % 400 == 0 || (y % 4 == 0 && y % 100 != 0)) {
return 1;
} else {
return 0;
}
}
} else if (m == 4 || m == 6 || m == 9 || m == 11) {
if (d > 30) { // d = 31 is incorrect
return 0;
}
}
return 1;
}
// Calculate the day of the week.
// Ref: Zeller's congruence https://ja.wikipedia.org/wiki/%E3%83%84%E3%82%A7%E3%83%A9%E3%83%BC%E3%81%AE%E5%85%AC%E5%BC%8F
int Zeller(int y, int m, int d) {
if (m == 1 || m == 2) {
m += 12;
y--;
}
int Y = y % 100;
int C = y / 100;
int Gamma = 5 * C + C / 4;
int h = (d + (26 * (m + 1)) / 10 + Y + Y / 4 + Gamma) % 7;
return h;
}
int main(void) {
int y, m, d;
printf("Input your birthday\n");
printf("-------------------\n");
printf("Year (yyyy): ");
scanf("%d", &y);
if (y < 1600 || y > 2020) {
printf("Error: Year must be between 1600 and 2020.\n");
exit(1);
}
printf("Month (mm) : ");
scanf("%d", &m);
if (m < 1 || m > 12) {
printf("Error: Month must be between 1 and 12.\n");
exit(1);
}
printf("Day (dd) : ");
scanf("%d", &d);
if (d < 1 || d > 31) {
printf("Error: Day must be between 1 and 31.\n");
exit(1);
}
printf("\n");
if (is_correct_day(y, m, d) == 0) {
printf("Error: %04d/%02d/%02d does not exist.\n", y, m, d);
exit(1);
}
int h = Zeller(y, m, d);
char days[7][10] = {
"Saturday", "Sunday" , "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday"
};
printf("%04d/%02d/%02d is %s.\n", y, m, d, days[h]);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment