质数相关
判断数字n是不是质数
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
boolean isPrime = true;
for (int i = 2; i < n; i ++){
if (n % i == 0) {
isPrime = false;
break;
}
}
if (isPrime && n != 1)
System.out.println("yes");
else
System.out.println("no");
}
}
输入样例
3
8
51
7
输出样例
8 is not prime
51 is not prime
7 is prime
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
while (n -- > 0) {
int x = sc.nextInt();
boolean isPrime = true;
for (int i = 2; i * i <= x; i ++)
if (x % i == 0){
isPrime = false;
break;
}
if (isPrime)
System.out.printf("%d is prime\n", x);
else
System.out.printf("%d is not prime\n", x);
}
}
}
参考
本文来自博客园,作者:逆袭怪,转载请注明原文链接:https://www.cnblogs.com/fghjktgbijn/p/17366584.html