暑假算法练习Day3

第三天!!!最近要开始归纳总结Python学习啦!!

1006 换个格式输出整数 (15 分)

让我们用字母 B 来表示“百”、字母 S 表示“十”,用 12...n 来表示不为零的个位数字 n(<10),换个格式来输出任一个不超过 3 位的正整数。例如 234 应该被输出为 BBSSS1234,因为它有 2 个“百”、3 个“十”、以及个位的 4。

输入格式:

每个测试输入包含 1 个测试用例,给出正整数 n(<1000)。

输出格式:

每个测试用例的输出占一行,用规定的格式输出 n

输入样例 1:

234

输出样例 1:

BBSSS1234

输入样例 2:

23

输出样例 2:

SS123

解题分析及代码:

今天的题目不是很难,这题考查的是如何求数的各个位,要熟练用%运算与/运算。

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <cmath>
using namespace std;
int main() {
    int n,b=0,s=0,g=0;
        cin >> n;
        b=n/100;
        s=n/10%10;
        g=n%10;
        for(int i=0;i<b;i++) cout << "B" ;
        for(int i=0;i<s;i++) cout << "S";
        for(int i=1;i<g+1;i++)cout << i;
        cout << endl;
    return 0;
}

1007 素数对猜想 (20 分)

让我们定义\(d_n为:d_n=p_{n+1}-p_n\),其中\(p_i\)是第i个素数。显然有\(d_1=1\),且对于\(n>1\)\(d_n\)是偶数。“素数对猜想”认为“存在无穷多对相邻且差为2的素数”。

现给定任意正整数N(<105),请计算不超过N的满足猜想的素数对的个数。

输入格式:

输入在一行给出正整数N

输出格式:

在一行中输出不超过N的满足猜想的素数对的个数。

输入样例:

20

输出样例:

4

解题分析及代码:

本题对素数如何判断是算法题常考的基础,务必掌握其函数。特别地,在函数体中,我定义了m来存sqrt(n),这样做的目的是,在for循环判断条件中不必一遍遍重复调用sqrt函数计算提高效率,另外若次数过多时,还有可能会造成超时的情况(曾经做过一题就是这种情况,大家需要注意!!)。

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <cmath>
using namespace std;
int IsPrime(int n){
    int m=sqrt(n);
    for(int i=2;i<=m;i++)
        if(n%i==0) return 0;
    return 1;
}
int main() {
    int n;
    int ans=0;
    cin >> n;
    for(int i=n;i-2>1;i--){
        if(IsPrime(i)&&IsPrime(i-2))
            ans++;
    }
    cout << ans << endl;
    return 0;
}
posted @ 2021-07-14 18:37  平和Kenn  阅读(83)  评论(0编辑  收藏  举报