Project Euler 19

几分钟应该解决的小问题……我依旧做了很久……算了……告诉自己慢慢来~


这次犯的错误

  1. 题目数据看错了 1900年写成了1999年……
  2. 额……我把c里面的 =  和 == 再次使用混乱……

第二个错误真是不可饶恕……


#include <stdio.h>

int
leap(year)
{
	if ((year % 100 == 0) && (year % 400 == 0))
		return 1;
	if ((year % 100 != 0) && (year % 4 == 0))
		return 1;
	return 0;
}

int M[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31}; 
int
main()
{
	int y, m, d, week = 0, ans = 0, monthDay;
	//force to count
	for (y=1900; y < 2001; y++)
	{
		for (m=1; m < 13; m++)
		{
			if (m == 2)
				monthDay = 28 + leap(y);
			else
				monthDay = M[m];
			for (d=0; d < monthDay; d++)
			{
				if ((d == 0) && (week == 6))
					ans ++;
				week = (week + 1) % 7;
			}
		}
	}
	//minus what i added during 1900
	//	problem is asking for from 1901 to 2001. so should minus the addtional part.
	y = 1900;
	for (m=1; m < 13; m++)
		{
			if (m == 2)
				monthDay = 28 + leap(y);
			else
				monthDay = M[m];
			for (d=0; d < monthDay; d++)
			{
				if ((d == 0) && (week == 6))
					ans --;
				week = (week + 1) % 7;
			}
		}
	printf("%d", ans);
}

比较简单。我在判断

if ((d == 0) && (week == 6))
这句……写错了……真是难以释怀……啊~蛋碎了


看看jason大牛写的……

用了Gaussian algorithm to determine day of week

这是非常明智的做法~不用一步一步运算了~

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
 
int day_of_week(int year, int month, int day) {
    // Using the Gaussian algorithm
    int d = day;
 
    double m = (double) ((month - 3) % 12 + 1);
    int Y;
    if(m > 10) Y = year - 1;
    else Y = year;
    int y = Y % 100;
    int c = (Y - (Y % 100)) / 100;
 
    int w = ((d+(int)floor(2.6*m-0.2)+y+ y/4 + c/4 -2*c))%7;
 
    return w; 
}
 
long months_start_range(int day, int year_start, int year_end) {
    unsigned long total = 0;
    int year, month;
    for(year = year_start; year < year_end; year++) {
        for(month = 1; month <= 12; month++) {
            if(day_of_week(year, month, 1)==day) total++;
        }
    }
    return total;
 
}
 
int main(int argc, char **argv) {
 
    int iter = 0;
    long total;
    while(iter < 100000) {
        total = months_start_range(0,1901,2000);
        iter++;
    }
    printf("Solution: %ld\n",total);
 
    return 0;
}

代码风格习惯还是蛮不错的~嗯……突然发现我的多个code都少了 return 0!!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值