java 判断一个数是否是素数

 

//check prime, find whether the input number is prime number or not

import java.util.Scanner;

public class Numbers {

    public static void main(String[] args) {
        int num;
        boolean flag = true;
        Scanner ip = new Scanner(System.in);
        System.out.print("Enter a number: ");
        num = ip.nextInt();
        for (int i = 2; i <= num / 2; i++) { // you can also use i <= Math.sqrt(num)
            if (num % i == 0)
                flag = false;
        }
        if (flag == true)
            System.out.println("It is prime number");
        else
            System.out.println("It is not a prime number");
        ip.close();
    }

}



OUTPUT:
Enter a number: 41
It is prime number

 

posted @ 2019-12-25 20:40  anobscureretreat  阅读(5202)  评论(0编辑  收藏  举报