Home >Java >javaTutorial >How to determine prime numbers using java

How to determine prime numbers using java

WBOY
WBOYforward
2023-04-27 21:58:057149browse

1. How to judge prime numbers: Use a number to divide 2 to sqrt (this number) respectively. If it can be divided evenly, it means that the number is not a prime number, otherwise it is a prime number.

sqrt refers to square, its function is to improve the operation speed, or not used.

public class sushu {
    public static void main(String[] args) {
        int count=0;
        for (int i=101;i<=200;i++) {                 //数的范围
            boolean a = false;                      //设立一个判断点
            for (int j = 2; j <=Math. sqrt(i); j++){  //判断是否是素数
                if(i%j==0){
                    a=false;
                    break;
                }else {
                    a=true;
                }
            }
        if(a==true)                             //判断点来确定素数,然后输出-
        {
            count++;
            System.out.println(i);
        }
        }
        System.out.println("素数的个数:"+count);
    }
}

2. After using the counter, if a certain number can be cleared, the counter will increase by itself. If the counter is 0 after the for loop is completed, it can be judged that the number is a prime number.

public static void isPrime(int n){
    int m = 0;
    for (int i = 2; i < n ; i++) {
        if(n % i==0)
            m++;
    }
    if (m == 0)
        System.out.println(n+"是素数");
    else
        System.out.println(n+"不是素数");
}

The above is the detailed content of How to determine prime numbers using java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete