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.”
特别提醒:请注意对1的判定,1不是素数。
Sample Input
3
Sample Output
This is a prime.
Hint
Source
ACcode:
package test;
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
int flag = 0;
if (t == 1)
{
System.out.println("This is not a prime.");
flag = 1;
}
for (int i = 2; i <= Math.sqrt(t); i++)
{
if (t % i == 0)
{
flag = 1;
System.out.println("This is not a prime.");
break;
}
}
if (flag == 0)
System.out.println("This is a prime.");
}
}