【蓝桥杯_C】个人训练(2019/11/19)

目录

 

问题 1004: [递归]母牛的故事

问题 1083: Hello, world!

问题 1084: 用筛法求之N内的素数。


问题 1004: [递归]母牛的故事

时间限制: 1Sec 内存限制: 128MB 提交: 32440 解决: 9415

题目描述

有一头母牛,它每年年初生一头小母牛。每头小母牛从第四个年头开始,每年年初也生一头小母牛。请编程实现在第n年的时候,共有多少头母牛?

输入

输入数据由多个测试实例组成,每个测试实例占一行,包括一个整数n(0<n<55),n的含义如题目中描述。
n=0表示输入数据的结束,不做处理。

输出

对于每个测试实例,输出在第n年的时候母牛的数量。
每个输出占一行。

样例输入

2
4
5
0

样例输出

2
4
6

自己写的时间超限emmmmm...

#include<iostream>
using namespace std;

int func(int n);
int main(){
	int n;
	while(cin>>n&&n!=0){	
		cout<<func(n)<<endl;
	}
	return 0;
}

int func(int n){
	if(n<4)
	return n;//第一二三年,各为1,2,3头 
	else
	return func(n-1)+func(n-3);//第n年为前一年的和前3年的相加 
}

换成C语言,把打表放在输入之前是不计入时间的,优化:

#include<stdio.h>
int func[60];

int main() {

	int n;
	for(int i=1; i<55; i++) {
		if(i<4)
			func[i]=i;
		else {
			func[i]=func[i-1]+func[i-3];
		}
	}
	while(~scanf("%d",&n)) {
		if(n==0)
			break;
		printf("%d\n",func[n]);
	}
	return 0;
}

 

问题 1083: Hello, world!

题目描述

This is the first problem for test. Since all we know the ASCII code, your job is simple: Input numbers and output corresponding messages.

输入

The input will contain a list of positive integers separated by whitespaces(spaces, newlines, TABs). Please process to the end of file (EOF). The integers will be no less than 32.

输出

Output the corresponding message. Note there is NOT a newline character in the end of output.

样例输入

72 101 108 108 111 44
32 119 111 114 108 100 33

样例输出

Hello, world!

解题思路:字符就是整数,整数就是字符。

<bits/stdc++.h>包含了全部的C++头文件。这样做题时直接敲上一句#include <bits/stdc++.h>而不是很多个#include。

但是有很多不编译器不支持,以下代码在DEV上编译:

#include<bits/stdc++.h>
using namespace std;
int main() {
	int data;
	while(cin>>data) {
		printf("%c",data);
	}
}

问题 1084: 用筛法求之N内的素数。

题目描述

用筛法求之N内的素数。

输入

N

输出

0~N的素数

样例输入

100

样例输出

2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97

任何一个大于1的自然数 N,如果N不为质数,那么N可以唯一分解成有限个质数的乘积

代码如下:

#include<stdio.h>
int main() {
	int i=3,n;
	scanf("%d",&n);
	if(n>2) {
		printf("2\n");
		while(i<=n) {
			int j;
			for(j=2; j<n; j++) {
				if(i%j==0&&i!=j) {
					break;
				} else if(i%j==0&&i==j) {
					printf("%d\n",j);
				}

			}
			i=i+2;//将 i 的跨步改为2,能省一半的内存

		}
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lucky__cc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值