問題描述:
試撰寫一個程式,由輸入一個整數,然後判別此數是否為質數。質數是指除了 1 和它本身之外,沒有其它的數可以整除它的數,例如, 2, 3, 5, 7 與 11 等皆為質數。

輸入說明
輸入一個正整數。

輸出說明:
質數顯示 YES ;非質數顯示 NO 。

範例:

 

Sample Input:

Sample Output:

23
37
39

YES
YES
NO

C++

#include <iostream>
#include <math.h>
using namespace std;

int main() {
	int in=0,out=0;
	bool flag=false;
	while (cin>>in)
	{
		 in==1? flag=true:flag=false;
		out=sqrt(in);
		for (int i = out; i>1; i--)
		{
			in%i==0?flag=true:flag=false;
			if (flag==true)break;
		}
		flag==true?cout<<"NO":cout<<"YES";
		
		
	}
	
    return 0;
}

python:

max=1000
f=[0,1]*(max//2+1)
f[0]=0;f[1]=1;f[2]=1;f[3]=1
h=int(max**0.5)
for i in range(3,h+1,2):
    if(f[i]==1):
        for j in range(i*i,max+1,i*2):
            f[j]=0
while True:
    try:
        n=int(input())
        if f[n]==1:print("YES")
        else:print("NO")
    except:break
arrow
arrow
    文章標籤
    python C++ ITSA
    全站熱搜
    創作者介紹
    創作者 趴趴熊日常 的頭像
    趴趴熊日常

    資工趴趴熊的小天地

    趴趴熊日常 發表在 痞客邦 留言(0) 人氣()