Home > Java > JavaBase > Java determines whether number is prime

Java determines whether number is prime

(*-*)浩
Release: 2019-11-13 11:12:38
Original
2469 people have browsed it

Java determines whether number is prime

There are several ways to determine whether a number is a prime number:

(1)Use between 2 and number-1 All numbers are divided by number. If one is divisible, it means that number is a non-prime number; unless all numbers are not divisible, it means that number is a prime number.                                                                                                                                                                                                                                                                                                       # Prime number; unless all numbers are not divisible, the number is prime. (3) Use all numbers between 2 and the square root of number to divide number. If any number can be divided evenly, it means that number is a non-prime number; unless all numbers cannot be divided evenly, it means that number is a prime number. .

The efficiency of these three methods is gradually improved. The implementation of the third method is listed below:

import java.util.Scanner;
public class Test2 {
    public static void main(String[] args) {
        int number; // 输入的数字
        Scanner input = new Scanner(System.in);
        System.out.println("请输入数字");
        number = input.nextInt(); // 输入数字
        if(isPrimeNumber(number)){
            System.out.println(number + "是一个素数");
        }
        else{
            System.out.println(number + "是一个非素数");
        }
    }
    public static boolean isPrimeNumber(int num){
        if(num < 2){
        System.out.println("数据错误");
        return false;
    }
    int k = (int)Math.sqrt(num); //num的平方根
    int i;
    for(i=2; i<=k; i++){ //依次用2..k之间的数去整除num,如果没有一个数能被整除,说明num是素数
        if(num % i == 0){
            break;
        }
    }
    if(i > k){
        return true;
    }
        return false;
    }
}
Copy after login

The above is the detailed content of Java determines whether number is prime. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template