Tuesday, March 10, 2015

How to Calculate Weekday

There is an algorithm problem, asks which day is it? Ex. Monday, Tuesday, or Sunday.
There is one formula, which tells the answer very effieciently.
int week(int y, int m, int d){    if (m < 3) {
        m += 12;
        y--;
    }
    
    int w = (d + 2 * m + 3 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400) % 7;
    return w;
}
The above is a C/C++ implementation code.
The following is a Swift implementation code.
func week(y:Int, m:Int, d:Int) ->Int {
    if (m < 3) {
        let m = 12 + m;
        let y = y - 1;
    }
    
    let w = (d + 2 * m + 3 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400) % 7;
    return w;
}