PAT B1013題解


1013 數素數 (20 分)
令 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>
#include<algorithm>
#include<cmath>
using namespace std;
const int maxn=1000010;
bool issunumble(int n){
	if(n<=1)
		return false;
	int t=(int)sqrt(1.0*n);
	for(int i=2;i<=t;i++){
		if(n%i==0){
			return false;
		}
	}
	return true;
}
int main(){
	int n,m,count=0,end=0;
	cin>>n>>m;
	for(int i=2;i<=maxn;i++){
		bool flag=false;
		if(issunumble(i)==true){
			count++;
			flag=true;
		}
		if(count>=n){
			break;
		}
		if(count>=n&&count<=m&&flag==true){
			end++;
			if(end%10==1){
				printf("%d",i);
			}
			else{
				printf(" %d",i);
			}
			if(end%10==0){
				printf("\n");
			}
		}
		
	}
	return 0;
} 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章