Home > Back-end >  write a code in c to find how many Fridays fell on the fifth of the month from 1 Jan 1801 to 31 Dec
write a code in c to find how many Fridays fell on the fifth of the month from 1 Jan 1801 to 31 Dec

Time:03-09

I was given this question to solve. My code outputs 316 but some suggest 345 is a correct answer. I don't know if my code works properly or not since I use the Sakamoto algorithm to calculate the weekday of a given day, month, and year. Since the actual date for 24 March, 2002 is Sunday instead of Wednesday (0 is Sunday ... 6 is Saturday). I add 3 (as a constant variable) in an algorithm. This is where I am a bit hesitant whether I make the right choice or not. However, I think that a shift does not affect anything so is this supposed to work?? Alternatively, I could set the weekday to Tuesday instead of Friday without any constant.

This is my code:

#include <stdio.h>
#include <math.h>

int howManyDays() {
    int sakamoto();
    
    int starting_weekday = 3;
    int result = sakamoto(24,3,2002,0);
    int constant = starting_weekday - result;

    int calculated_year = 1801;
    int calculated_month = 1;
    int count = 0;

    do {
        int calculated_weekday = sakamoto(5, calculated_month, calculated_year, constant);
        //int calculated_weekday = (calculated_day constant day_in_months[calculated_month-1]) % 7;

        if (calculated_weekday == 5) {
            count  = 1;
        }

        calculated_month  = 1;

        if (calculated_month == 12) {
            calculated_month = 1;
            calculated_year  = 1;
        } 

    } while(!(calculated_month == 1 && calculated_year == 2001));
    return count;
}

int sakamoto(int d, int m, int y, int c) {
    int offset[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4}; // 0->Sunday ... 2->Tuesday ... 6->Saturday
    y -= m < 3;

    return (y   y / 4 - y / 100   y / 400   offset[m - 1]   d   c) % 7;

}


int main() {
    int a = howManyDays();
    printf("result: %d", a);
}

Could anyone confirm whether what I think is correct or completely false?? Thanks in Advance, Hope you have a wonderful time :)

CodePudding user response:

Your months range from 1 to 11. Since you're not counting Fridays in December, your results are off by about 1/12th and indeed 345*11/12 = 316.25.

  • Related