close
質數就是指在大於1的自然數中,除了1和此整數自身外,無法被其他自然數整除的數,換句話說就是只有1和本身兩個因數的數,但要注意0,1並非質數,所以使用迴圈必須從2開始看是不是輸入整數有被整除,整除的話就非質數了
1.Python
def compute(n):
for v in range(2,n):
if(n%v==0):
return False
else:
return True
a = eval(input())
if compute(a):
print("Prime")
else:
print("Not Prime")
2.JAVA
import java.util.Scanner;
import java.lang.*;
public class prime
{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n;
boolean judge=false;
while(sc.hasNext()){
judge=false;
n=scan.nextInt();
for(int i=2;i<a;i++){
if(a%i==0){
judge=true;
System.out.println("非質數");
break;
}
}
if(judge == false){
System.out.println("質數");
}
}
}
}
文章標籤
全站熱搜
留言列表