🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# Java 程序:打印备用素数 > 原文: [https://beginnersbook.com/2019/04/java-program-to-print-alternate-prime-numbers/](https://beginnersbook.com/2019/04/java-program-to-print-alternate-prime-numbers/) 在本教程中,我们将编写一个 Java 程序,以**显示备用素数,直到给定值**。 ## Java 示例:打印备用素数 在以下示例中,我们有两个用户定义的方法:`checkPrime()`和`printAltPrime()`。 `checkPrime()`方法检查作为参数传递的数字是否为素数,如果数字为素数,则此方法返回 1,否则返回`false`。 `printAltPrime()`方法打印备用素数,直到作为参数传递的值。 请阅读注释以了解程序的逻辑。 ```java class JavaExample { //method for checking prime number static int checkPrime(int num) { int i, flag = 0; for(i = 2; i<= num / 2; i++) { if(num % i == 0) { flag = 1; break; } } /* If flag value is 0 then the given number num * is a prime number else it is not a prime number */ if(flag == 0) return 1; else return 0; } //Method for printing alternate prime numbers static void printAltPrime(int n) { /* When the temp value is odd then we are * not printing the prime number and when it is * even then we are printing it, this way we are * displaying alternate prime numbers */ int temp = 2; for(int num = 2; num <= n-1; num++) { //checking each number whether it is prime or not if (checkPrime(num) == 1) { // if temp is even then only print the prime number if (temp % 2 == 0) System.out.print(num + " "); temp ++; } } } public static void main(String[] args) { int num = 20; System.out.print("Alternate prime numbers upto " + num+" are: "); printAltPrime(num); } } ``` **输出:** ![Java Program to display alternate prime numbers](https://img.kancloud.cn/b9/1c/b91c530932a876bf393834bc537d2362_670x214.jpg) #### 相关的 Java 示例 1. [Java 程序:显示前`n`个素数](https://beginnersbook.com/2014/01/java-program-to-display-first-n-or-first-100-prime-numbers/) 2. [Java 程序:检查素数](https://beginnersbook.com/2014/01/java-program-to-check-prime-number/) 3. [Java 程序:检查一个数字是否完美平方](https://beginnersbook.com/2019/02/java-program-to-check-if-given-number-is-perfect-square/) 4. [Java 程序:查看 Armstrong 数字](https://beginnersbook.com/2017/09/java-program-to-check-armstrong-number/)