素數是什么大家應該都知道,一個數是不是素數也很簡單。
一下是代碼,分別由兩個函數。一個函數實現判斷一個數是不是素數,另外一個函數實現輸出小於等於一個特定數字的所有素數。
#include "stdafx.h" #include <iostream> using namespace std; //Display_sushu(int m)函數輸出小於等於m的所有素數 void Display_sushu(int m) { int n=0; int i; for(int j=1;j<=m;j++) { if (j==3||j==2||j==1) //這里是j不是m,下面也是一樣的 { cout<<j<<"是素數"<<endl; continue; } n=j/2; for (i=2;i<=n;i++) { if (j%i==0) { //cout<<m<<"不是素數"<<endl; break; } } if (i>n) cout<<j<<"是素數"<<endl; } } //Is_sushu(int m)函數判斷m是不是素數 void Is_sushu(int m) { int n=m/2; if (m==1||m==2) { cout<<m<<"是素數"<<endl; return; } for (int i=2;i<=n;i++) { if (m%i==0) { cout<<m<<"不是素數"<<endl; return; } } cout<<m<<"是素數"<<endl; } int main() { int m; cin>>m; Is_sushu(m); cin>>m; Display_sushu(m); return 0; }
截圖:
PS:n=m/2即循環次數的控制,其實還可以寫成n=sqrt(m),但是要求數據類型有要求。且需要頭文件cmath。
網摘:VC 2008后為重載函數,原型為 float sqrt (float),double sqrt (double),double long sqrt(double long)
注意沒有sqrt (int),但是返回值可以為int。
這樣子循環次數更少,效率更高。
可以這樣改的原因就是,一個數m如果可以分解成兩個數(因子)的乘積(除開1和它本身),那么至少有一個因子小於等於sqrt(m),另外一個因子大於等於sqrt(m),最特別的兩個因子都等於sqrt(m),即sqrt(m)*sqrt(m)。