题目:
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<)
拓展:基本所有素数题。