The Gregorian Calendar Algorithm

This section describes the algorithm to calculate the day of the week based on leap year rules. The algorithm can be implemented with isGregorianLeapYear(), dayOfYear() and dayOfWeek() functions.

The Gregorian calendar is not so difficult to calculate. Here is a simple algorithm to determine the day of the week for a given Gregorian date, month and year:

• Determine if the given year is a leap year based on the leap year rules. See the isGregorianLeapYear() function below.
• Determine the day of the year based on the given date and month with the help of the isGregorianLeapYear() function. See the dayOfYear() function below.
• Determine the day of the week with the code with the help of the dayOfYear() function. See the dayOfWeek() function below.

The isGregorianLeapYear() function returns true if the given year is a leap year:

```   public static boolean isGregorianLeapYear(int year) {
boolean isLeap = false;
if (year%4==0) isLeap = true;
if (year%100==0) isLeap = false;
if (year%400==0) isLeap = true;
return isLeap;
}
```

The dayOfYear() function returns the day of the year for any given year, month and day:

```   public static int dayOfYear(int y, int m, int d) {
int c = 0;
for (int i=1; i<m; i++) { // Number of months passed
c = c + daysInGregorianMonth(y,i);
}
c = c + d;
return c;
}
public static int daysInGregorianMonth(int y, int m) {
int d = daysInGregorianMonth[m-1];
if (m==2 && isGregorianLeapYear(y)) d++;
return d;
}
```

The dayOfWeek() function returns the day of the week for any given year, month and day:

```   public static int dayOfWeek(int y, int m, int d) {
int w = 1; // 01-Jan-0001 is Monday, so base is Sunday
y = (y-1)%400 + 1; // Gregorian calendar cycle is 400 years
int ly = (y-1)/4; // Leap years passed
ly = ly - (y-1)/100; // Adjustment
ly = ly + (y-1)/400; // Adjustment
int ry = y - 1 - ly; // Regular years passed
w = w + ry; // Regular year has one extra week day
w = w + 2*ly; // Leap year has two extra week days
w = w + dayOfYear(y,m,d);
w = (w-1)%7 + 1;
return w;
}
```