练习题目二
素数判断
A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5 and 7.
Write a program which reads a list of N integers and prints the number of prime numbers in the list.
Input
The first line contains an integer N, the number of elements in the list.
N numbers are given in the following lines.
Output
Print the number of prime numbers in the given list.
Constraints
1 ≤ N ≤ 10000
2 ≤ an element of the list ≤ 108
Sample Input 1
5
2
3
4
5
6
Sample Output 1
3
Sample Input 2
11
7
8
9
10
11
12
13
14
15
16
17
Sample Output 2
4
运行代码
#include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int b=0,m,count;
for(int i=0;i<n;i++){
cin>>m;
count=1;
for(int i=2;i<m;i++)
{
if(m%i==0)
count=0;
break;
}
if(count==1&&m!=1)
b++;
}
cout<<b;
return 0;
}
题目思考
所谓素数既是定义为在大于1的自然数中,除了1和它本身以外不再有其他因数。所以我使用嵌套循环,使他除以2到自己本身减1的所有数,若都除不尽,则素数数量+1,。
错误及调试
第一次编写好程序进行运行,运行结果出错如图。
所以我进行调试,在调试过程中,我发现不论if里的条件成立与否,break都会运行,所以导致程序出错,调试如图。
所以,错误原因既是在if后,没有打出{ }导致if条件只对第一条代码生效,因此我修改代码后,程序运行正确。