Problem 19 : Counting Sundays (5%)

link

Description

original

You are given the following information, but you may prefer to do some research for yourself.

  • 1 Jan 1900 was a Monday.
  • Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine.
  • A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?

간략해석

조건에 맞는 날짜를 카운팅하시오.

Idea & Algorithm

naive idea

단순 구현 문제입니다. 윤년 체크의 경우에는 my함수를 사용하면 된다.

요일의 경우에는 7진법으로 생각하면 된다.

advanced idea

source code

#include <stdio.h>

int mon[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};

int my(int n){
    if(n%4==0&&(n%100!=0||n%400==0)){
        return 1;
    }
    return 0;
}

int main(){
    int st = 2;
    int cnt = 0;
    for(int i = 1901; i <= 2000 ; i++){
        for(int j = 1 ; j <= 12 ; j++){
            if(st==6) cnt++;
            st += mon[j];
            if(j == 2) st += my(i);
            st %= 7;
        }
    }
    printf("%d",cnt);
}

Leave a Comment