算法训练 黑色星期五
时间限制:1.0s 内存限制:512.0MB
问题描述
有些西方人比较迷信,如果某个月的13号正好是星期五,他们就会觉得不太吉利,用古人的说法,就是“诸事不宜”。请你编写一个程序,统计出在某个特定的年份中,出现了多少次既是13号又是星期五的情形,以帮助你的迷信朋友解决难题。
说明:(1)一年有365天,闰年有366天,所谓闰年,即能被4整除且不能被100整除的年份,或是既能被100整除也能被400整除的年份;(2)已知1998年1月1日是星期四,用户输入的年份肯定大于或等于1998年。
输入格式:输入只有一行,即某个特定的年份(大于或等于1998年)。
输出格式:输出只有一行,即在这一年中,出现了多少次既是13号又是星期五的情形。
输入输出样例
样例输入
1998
样例输出
3
#include <stdio.h>
int days_of_month[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int is_leap(int year)
{
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
return 1;
else
return 0;
}
int day_of_week(int year, int month, int day)
{
int days_to_19980101 = 0;
for (int y = 1998; y < year; ++y)
{
if (is_leap(y))
days_to_19980101 += 366;
else
days_to_19980101 += 365;
}
for (int m = 1; m < month; ++m)
{
days_to_19980101 += days_of_month[m];
if (m == 2 && is_leap(year))
days_to_19980101 += 1;
}
days_to_19980101 += day - 1;
return (days_to_19980101 % 7 + 4) % 7;
}
int main()
{
int year;
int cnt = 0;
scanf("%d", &year);
for (int month = 1; month <= 12; ++month)
{
if (day_of_week(year, month, 13) == 5)
cnt++;
}
printf("%d", cnt);
return 0;
}