Java程序打印素数
任何大于1且只有两个因数和1本身的整数都称为质数。除了这两个数字外,它没有正除数。例如-
7 = 1 × 7
很少素数是− 1、2、3、5、7、11等。
算法
1. Take integer variable A2. 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
以上是 Java程序打印素数 的全部内容, 来源链接: utcz.com/z/321697.html