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