craft code to find a weekday name given a date in proleptic gregorian calendar, without…
- User
craft code to find a weekday name given a date in proleptic gregorian calendar, without using timestamps. *str weekday(in year,in month,int day) {
} test with str=weekday(2024,05,15); printf("%s", str);
Assistant
Here is a C function that calculates the weekday name given a date in the proleptic Gregorian calendar without using timestamps. The function uses Zeller's Congruence algorithm to calculate the day of the week.
c#include <stdio.h> #include <string.h> char *weekday(int year, int month, int day) { static char *weekdays[] = {"Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}; int t = (day + ((13 * (month + 1)) / 5) + year + (year / 4) - (year / 100) + (year / 400)) % 7; return weekdays[t]; } int main() { char *str = weekday(2024, 5, 15); printf("%s\n", str); return 0; }This program will print "Wednesday" when run, which is the correct weekday for May 15, 2024.
The Zeller's Congruence algorithm calculates the day of the week for any date in the Gregorian calendar. The formula used is:
h = (q + 13*(m+1)/5 + d + y + y/4 - y/100 + y/400) mod 7
- User
if it would work beyond 0ad, with negative years
Assistant
The Zeller's Congruence algorithm can be modified to work with negative years (i.e., years before the common era) by adjusting the calculation of the year.
Here's the modified function:
cchar *weekday(int year, int month, int day) { static char *weekdays[] = {"Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}; int y = year; if (year < 1) { y = year - 1; } int t = (day + ((13 * (month + 1)) / 5) + y + (y / 4) - (y / 100) + (y / 400)) % 7; if (year < 1) { t = (t + 1) % 7; } return weekdays[t]; }This modified function works by subtracting 1 from the year if it's negative, performing the calculation, and then adjusting the result by adding 1 (and taking the modulus) if the original year was negative. This adjustment is necessary because the Gregorian calendar has a year 1 BC, but the Zeller's Congruence algorithm assumes a year 0.
With this modification, the function should work correctly for dates in the proleptic Gregorian calendar with negative years.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.