Analysis:Friday the Thirteenth

本文介绍了一个通过编程方式计算从1900年开始的400年内每个月13号落在星期五的次数的方法。该程序使用C语言实现,考虑了闰年和平年的不同,并通过调整星期计算来准确获取每月13号的日期。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Brute force is a wonderful thing. 400 years is only 4800 months, so it is perfectly practical to just walk along every month of every year, calculating the day of week on which the 13th occurs for each, and incrementing a total counter.
#include <stdio.h>
#include 
<stdlib.h>
#include 
<string.h>
#include 
<assert.h>

int
isleap(
int y)
{
    
return y%4==0 && (y%100 != 0 || y%400 == 0);
}


int mtab[] = 312831303130313130313031 };

/* return length of month m in year y */
int
mlen(
int y, int m)
{
    
if(m == 1)    /* february */
        
return mtab[m]+isleap(y);
    
else
        
return mtab[m];
}


void
main(
void)
{
    FILE 
*fin, *fout;
    
int i, m, dow, n, y;
    
int ndow[7];

    fin 
= fopen("friday.in""r");
    fout 
= fopen("friday.out""w");
    assert(fin 
!= NULL && fout != NULL);

    fscanf(fin, 
"%d"&n);

    
for(i=0; i<7; i++)
        ndow[i] 
= 0;

    dow 
= 0;    /* day of week: January 13, 1900 was a Saturday = 0 */
    
for(y=1900; y<1900+n; y++{
        
for(m=0; m<12; m++{
            ndow[dow]
++;
            dow 
= (dow+mlen(y, m)) % 7;
        }

    }


    
for(i=0; i<7; i++{
        
if(i)
            fprintf(fout, 
" ");
        fprintf(fout, 
"%d", ndow[i]);
    }

    fprintf(fout, 
" ");

    exit(
0);
}


 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值