1013 数素数 (20 分)

题目链接

  1. 查找区间中的素数然后按格式输出。
  2. 素数的题都快做烂了,官方好像出过好几道了。
  3. python是真的慢,我也到网上找了几份代码,那个测试点都超时了。

c++代码

#include <iostream>
#include<string>
#include<vector> 
#include<math.h>
using namespace std;

int judge(int n) {
	if (n < 2)
		return 0;//非素数
	for (int i = 2; i*i <= n; i++) {
		if (n%i == 0)
			return 0;//非素数
	}
	return 1;  
}

int main() {
	int m, n;
	int count = 0; //记录素数的个数
	vector<int> res;
	cin >> m >> n;
	int i = 0;
	while (count < n) {
		i++;  //记录当前要判断的的数
		if (judge(i) == 1) {	//i是素数
			count++;  //记录当前素数的个数
			if (count >= m)
				res.push_back(i);
		}

	}
	count = 0;
	for (int i = 0; i < res.size(); i++) {
		count++;
		if (i < res.size() - 1 && count < 10)
			cout << res[i] << " ";
		else
		{
			cout << res[i] << endl;
			count = 0;
		}
	}
	return 0;
}
复制代码

python3代码

mport math
def judge(n):
    if(n< 2):
        return 0
    max = int(math.sqrt(n))
    for i in range(2,max+1):
        if(n%i==0):
            return 0
    return 1

def main():
    s = input().split()
    num = list(map(int,s))
    res = []
    i = 2
    count = 0 # 计算素数的个数
    while(count < num[1]):
        if(judge(i) == 1):
            count += 1
            if(count >= num[0]):
                res.append(i)
        i += 1
    count = 0
    for i in range(res.__len__()):
        count+=1
        if(count < 10 and i != res.__len__() -1):
            print(res[i],end=' ')
        else:
            print(res[i])
            count = 0
main()
复制代码

转载于:https://juejin.im/post/5ce57c2af265da1b70048073

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值