20201207大一集训题l题求质数(素数)

题目:
Give you a lot of positive integers, just to find out how many prime numbers there are.
Input
There are a lot of cases. In each case, there is an integer N representing the number of integers to find. Each integer won’t exceed 32-bit signed integer, and each of them won’t be less than 2.
Output
For each case, print the number of prime numbers you have found out.
翻译:
给你许多正整数,仅仅找到有多少prime numbers(素数)。
输入
多组输入。
每组有n个整数给你,都是32位有符号的int类型,每组都不会小于2.
输出
对于每组,每行输出你所找到的素数的数。
原思路:
用根号n去计算,普通求素数的方法。(其实你会发现,到后面还是会超时)
源代码:

#include<stdio.h>
#include<math.h>
int main()
{
	int n;
	int count=0;
	while(~scanf("%d",&n)){
		while(n--){
		int a;
		scanf("%d",&a);
		for(int i=1;i<sqrt(a);i++){
			if(a%i==0) count++;
		} 
	} 
	printf("%d\n",count);
	}
	return 0;
} 

还是超时。
正确代码:

#include<stdio.h>
#include<math.h>
int main()
{
	int n;
	while(~scanf("%d",&n)){
		int count=0;
		int copy=n;
		while(n--){
		int a;
		scanf("%d",&a);
		for(int i=2;i<=sqrt(a);i++){
			if(a%i==0){count++;break;}
		} 
	} 
	printf("%d\n",copy-count);
	}
	return 0;
} 

反思:
有时你需要逆向思维,直接查找非素数,然后计数,用break跳出,最后用总数减去非素数,就是结果了。(这种方法好处在于,灵活运用break语句减少运算,很jb强->o<)
拓展:基本所有素数题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值