中国大学MOOC-陈越、何钦铭-数据结构-起步能力自测题
自测-1 打印沙漏
本题要求你写个程序把给定的符号打印成沙漏的形状。例如给定17个“*”,要求按下列格式打印
所谓“沙漏形状”,是指每行输出奇数个符号;各行符号中心对齐;相邻两行符号数差2;符号数先从大到小顺序递减到1,再从小到大顺序递增;首尾符号数相等。
给定任意N个符号,不一定能正好组成一个沙漏。要求打印出的沙漏能用掉尽可能多的符号。
输入格式:
输入在一行给出1个正整数N(≤1000)和一个符号,中间以空格分隔。
输出格式:
首先打印出由给定符号组成的最大的沙漏形状,最后在一行中输出剩下没用掉的符号数。
输入样例:
19 *
输出样例:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>
using namespace std;
int main()
{
int n;
char c;
cin >> n >> c;
int t = (int)sqrt((float)((n + 1) / 2));
if(n==1){
cout<<c<<endl;
cout<<"0";
return 0;
}
for (int i = 0; i < t; i++)
{
for (int m = 0; m < i; m++)
cout << " ";
for (int j = 1; j <= 2 * (t - i) - 1; j++)
{
cout << c;
}
if(t!=1)
cout << endl;
}
for (int i = t-2; i >=0; i--)
{
for (int m = 0; m < i; m++)
cout << " ";
for (int j = 1; j <= 2 * (t - i) - 1; j++)
{
cout << c;
}
if(i!=0)
cout << endl;
}
if (2*t * t != n + 1)
{
cout << endl;
cout << n - 2 * t * t + 1;
}
return 0;
}
自测-2 素数对猜想
让我们定义
素数对猜想”认为“存在无穷多对相邻且差为2的素数”。
现给定任意正整数N(<100000),请计算不超过N的满足猜想的素数对的个数。
输入格式:
输入在一行给出正整数N。
输出格式:
在一行中输出不超过N的满足猜想的素数对的个数。
输入样例:
20
输出样例:
4
#include <stdio.h>
#include<iostream>
#include<math.h>
using namespace st