高斯日记 蓝桥杯

欢迎访问我的新博客:http://www.milkcu.com/blog/

原文地址:http://www.milkcu.com/blog/archives/1370502600.html

标题:高斯日记 - 蓝桥杯

作者:MilkCu(http://blog.csdn.net/milkcu

内容:2013年第四届蓝桥杯软件大赛预赛第一题。

题目描述

题目标题: 高斯日记
大数学家高斯有个好习惯:无论如何都要记日记。
他的日记有个与众不同的地方,他从不注明年月日,而是用一个整数代替,比如:4210
后来人们知道,那个整数就是日期,它表示那一天是高斯出生后的第几天。这或许也是个好习惯,它时时刻刻提醒着主人:日子又过去一天,还有多少时光可以用于浪费呢?
高斯出生于:1777年4月30日。
在高斯发现的一个重要定理的日记上标注着:5343,因此可算出那天是:1791年12月15日。
高斯获得博士学位的那天日记上标着:8113
请你算出高斯获得博士学位的年月日。

提交答案的格式是:yyyy-mm-dd, 例如:1980-03-21
请严格按照格式,通过浏览器提交答案。
注意:只提交这个日期,不要写其它附加内容,比如:说明性的文字。

算术方法

用整除和取余列个算式,就出来了。但要注意,闰年问题高斯出生的那天也算一天

C语言实现

该题也可用C语言实现,对于区区小填空题,用笔算算就够了。但是我还是把C语言代码搬上来吧。写的有点繁琐,暂时没找到好方法。

# include <stdio.h>
int isLeap(int y);
int nday(int y, int m, int d);
void ymd(int n);
int main(void)
{
	int n = 8113;
	int yb = 1777, mb = 4, db = 30;    //birth
	n = n - 1 + nday(yb, mb, db);
	int yp, np;    //print
	for(int i = yb; n > 0; i++) {
		yp = i;
		np = n;
		if(isLeap(i)) {
			n -= 366;
		} else {
			n -= 365;
		}
	}
	printf("%d-", yp);
	ymd(np);
	return 0;
}
int nday(int y, int m, int d)
{
	int n = 0;
	int a[2][12] = {{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, 
	                {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}};
	for(int i = 0; i < (m - 1); i++) {
		n += a[isLeap(y)][i];
	}
	n += d;
	return n;
}
void ymd(int n)
{
	int a[2][12] = {{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, 
	                {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}};
	int mp, dp;
	for(int i = 0; n > 0; i++) {
		dp = n;
		mp = i;
		n -= a[isLeap(i)][i];
	}
	printf("%d-%d\n", mp + 1, dp);
}
int isLeap(int y)
{
	if((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0)) {
		return 1;
	} else {
		return 0;
	}
}

二维数组存放月份天数,自我感觉还是挺巧妙的。

最后答案

1799-07-16

扩展

看了高斯,我很惭愧,那我也写个程序算算我活了多少天了吧。

# include <stdio.h>
int nday(int y, int m, int d);
int isLeap(int y);
int main(void)
{
	int yb = 1992, mb = 9, db = 30;    //birth
	int yn = 2013, mn = 6, dn = 6;    //now
	int n = 1;
	for(int i = yb; i < yn; i++) {
		if(isLeap(i)) {
			n += 366;
		} else {
			n += 365;
		}
	}
	n = n - nday(yb, mb, db) + nday(yn, mn, dn);
	printf("I have been for %d days.\n", n);
	return 0;
}
int nday(int y, int m, int d)
{
	int n = 0;
	int a[2][12] = {{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}, 
	                {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}};
	for(int i = 0; i < (m - 1); i++) {
		n += a[isLeap(y)][i];
	}
	n += d;
	return n;
}
int isLeap(int y)
{
	if((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0)) {
		return 1;
	} else {
		return 0;
	}
}

这样一算,我已经活了7555天了。

(全文完)

原文地址:https://www.cnblogs.com/milkcu/p/3808927.html