#C++初學記錄(素數判斷2)


素數判斷2 比較簡單的算法,沒有技術含量
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

對於算法

素數判斷1中,我使用暴力代碼判斷素數,這無疑是花費時間最長,編寫難度最易的代碼,在學習的過程中,我發現變成和數學緊密相連,就比如這個素數判斷的題目,運用數學方法可以使計算機更快速的跑完程序。
運行的代碼

#include<iostream>
#include<math.h>
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;
        if(m!=2&&m%2==0)
        count=0,break;
	for(int i=2;i<=sqrt(m);i++)
	{
		if(m%2==0) 
		{
			count=0;
			break;
		}
		if(m*m%i==0){ 
		count=0;
		break;} 
	}
	if(count==1&&m!=1)
	b++;
    }  
    cout<<b;
	return 0; 

}
	

思考過程

素數是因子為1和本身的數, 如果數m不是素數,則還有其他因子,其中的因子,假如為a,b.其中必有一個大於sqrt(m) ,一個小於 sqrt(m)。也就是說,判斷素數只需判斷2到sqrt(m)即可,即將判斷次數減少一半,來縮短程序運行時間。
素數還有一個特性,就是說除了2以外的所有素數都是偶數。因此,在程序的開始提前將一半偶數排除再外也能縮短大部分的程序運行時間。另外用上面我寫的程序中count?=0break能使條理更加清晰。

錯誤及調試
剛開始使用sqrt(m)的時候出現了一個錯誤,就是一組數據的輸入Sample Input 2本應輸出4,但是程序輸出了5

但是經過調試我發現,錯誤的原因是因為在for循環中,i的終止條件應該是小於等於而不是小於,因為sqrt(m)也能成為一個判定的數據。

修改后,既是正確的輸出程序.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM