Algorithm, Data structure/Solved Algorithmic Problem

Project Euler #19 - Counting Sundays

JaykayChoi 2016. 6. 28. 22:51

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)?




출처: https://projecteuler.net/problem=19


1901년 1월 1일 ~ 2000년 12월 31일 에서 매월 1일이 일요일이 경우가 총 몇 번인지 계산하는 문제입니다.

전에 USACO 에서 푼 문제와 비슷한 문제네요.

윤년을 고려하여 각 달의 날수를 구하는 것이 중요한 문제입니다.




my solving

c++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <fstream>
#include <iostream>
#include <algorithm>
using namespace std;
 
int calcDaysOfMonth(int month, int year)
{
    switch (month)
    {
    case 2:
        if ((year % == && year % 100 != 0|| year % 400 == 0)
            return 29;
        else
            return 28;
    case 4:
    case 6:
    case 9:
    case 11:
        return 30;
    default:
        return 31;
    }
}
 
int main()
{
    //1.1.1901 is Tuesday
    int now = 2;
    int ret = 0;
    for (int i = 1901; i < 2001; i++)
    {
        for (int month = 1; month < 13; month++)
        {
            if ((now + 1) % == 00)
                ret++;
            now = (now + calcDaysOfMonth(month, i)) % 7;
        }
    }
 
    cout << ret << endl;
    system("pause");
    return 0;
}
cs