任何大于1且只有两个因数和1本身的整数都称为质数。除了这两个数字外,它没有正除数。例如-
7 = 1 × 7
很少素数是− 1、2、3、5、7、11等。
1. Take integer variable A 2. Divide the variable A with (A-1 to 2) 3. If A is divisible by any value (A-1 to 2) it is not prime 4. Else it is prime
import java.util.Scanner; public class PrimeNumber { public static void main(String args[]){ int loop, number; int prime = 1; Scanner sc = new Scanner(System.in); System.out.println("Enter a number ::"); number = sc.nextInt(); for(loop = 2; loop < number; loop++) { if((number % loop) == 0) { prime = 0; } } if (prime == 1) System.out.println(number+" is a prime number"); else System.out.println(number+" is not a prime number"); } }
输出结果
Enter a number :: 2 2 is a prime number