1. 程式人生 > >PAT乙級1013數素數

PAT乙級1013數素數

題目如下:

令 P ​i ​​ 表示第 i 個素數。現任給兩個正整數 M≤N≤10 ​4 ​​ ,請輸出 P ​M ​​ 到 P ​N ​​ 的所有素數。

輸入格式: 輸入在一行中給出 M 和 N,其間以空格分隔。

輸出格式:

輸出從 P ​M ​​ 到 P ​N ​​ 的所有素數,每 10 個數字佔 1 行,其間以空格分隔,但行末不得有多餘空格。

輸入樣例: 5 27 輸出樣例: 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103

程式碼如下:

#include <iostream>
using namespace std;
bool isprime(int a) { for(int i=2;i*i<=a;i++) if(a%i==0) return false; return true; } int main() { int m,n,flag=1; cin>>m>>n; int num=2,cnt=0,a[10000]={0}; while(cnt<n) { if(isprime(num)) { a[cnt++]=num; } num++
; } cnt=0; for(int i=m-1;i<n;i++) { cnt++; cout<<a[i]; if(cnt%10!=0&&cnt!=n-m+1) cout<<" "; if(cnt%10==0) cout<<endl; } return 0; }

求素數的模板函式:

bool isprime(int a)
{
    for(int i=2;i*i<=a;i++)
        if(a%i==0) return false
; return true; }

總結: 求素數有兩種方法:篩選法和開根號法

  • 篩選法:從小到大篩去一個已知素數的所有倍數。依次刪除可被2整除,3整除。。。。的數字,剩下的則為素數 。

  • 開根號法:如果一個數(>2),對這個數求平方根,如果這個數能被這個數的平方根到2之間的任何一個(只要有一人就行)整除說明就不是質數,如果不能就說明是質數!