质数相关

判断数字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);
        }
    }
}

参考

posted on 2023-05-01 15:39  逆袭怪  阅读(3)  评论(0编辑  收藏  举报