Home > Java > javaTutorial > How to determine whether a number is prime in java

How to determine whether a number is prime in java

王林
Release: 2020-04-28 11:32:19
Original
12008 people have browsed it

How to determine whether a number is prime in java

What are prime numbers?

Prime numbers are also called prime numbers, and there are infinite numbers. A prime number is defined as a natural number greater than 1 that has no other factors except 1 and itself. Such a number is called a prime number.

(Video tutorial recommendation: java video)

Purpose:

Judge whether a number is a prime number

Judgment idea:

1. First, use the Math.sqrt() function to square the number, such as [Math.sqrt(n)];

2. Then use the for loop and if statement to make the remainder judgment. That’s it.

Specific example:

import java.util.Scanner;
public class TestWork {
	public static void main(String[] args) {
		boolean isPrime = true;
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入一个正整数");
		int num = sc.nextInt();
		if (num > 0) {
			int k = (int) Math.sqrt(num);//k为num的正平方根,取整数
			for (int i = 2; i <= k; i++) {
				if (num % i == 0) {
					isPrime = false;//不是素数
					break;
				}
			}
		}
		if (isPrime) {
			System.out.println(num + "是素数");
		} else {
			System.out.println(num + "不是素数");
		}
	}
}
Copy after login

Recommended tutorial: java entry program

The above is the detailed content of How to determine whether a number is prime in java. 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