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

How to determine prime numbers using java

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2023-04-27 21:58:05
forward
7202 people have browsed it

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);
    }
}
Copy after login

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+"不是素数");
}
Copy after login

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!

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
Install JAVA
From 1970-01-01 08:00:00
0
0
0
Unable to install java
From 1970-01-01 08:00:00
0
0
0
Can java be used as the backend of the web?
From 1970-01-01 08:00:00
0
0
0
Is this in Java language?
From 1970-01-01 08:00:00
0
0
0
Help: JAVA encrypted data PHP decryption
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template