C语言实验——判断素数(循环结构)
Time Limit: 1000 ms
Memory Limit: 65536 KiB
Problem Description
从键盘上输入任意一个正整数,然后判断该数是否为素数。
如果是素数则输出"This is a prime."
否则输出“This is not a prime.”
Input
输入任意一个正整数n(1 <= n <= 1000000)。
Output
判断n是否为素数,并输出判断结果:
如果n是素数则输出"This is a prime."
否则输出“This is not a prime.”
Sample Input
3
Sample Output
This is a prime.
package practice;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
int n,i,f=1;
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
if(n==1) {
System.out.println("This is not a prime.");
}
else if(n==2) {
System.out.println("This is a prime.");
}
else {
for(i=2;i<n;i++) {
if(n%i==0) {
f=0;
}
}
if(f==0) {
System.out.println("This is not a prime.");
}
else {
System.out.println("This is a prime.");
}
}
sc.close();
}
}