⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 primenumber.java

📁 此源码为机械工业出版社出版的《Java语言程序设计》第三版所配套的书中所有源代码。
💻 JAVA
字号:
// PrimeNumber.java: Print first 50 prime numbers
public class PrimeNumber
{
  // Main method
  public static void main(String[] args)
  {
    int count = 1; // Count the number of prime numbers
    int number = 2; // A number to be tested for primeness
    boolean isPrime = true;  // If the current number is prime?

    System.out.println("The first 50 prime numbers are \n");

    // Repeatedly test if a new number is prime
    while (count <= 50)
    {
      // Assume the number is prime
      isPrime = true;

      // Set isPrime to false, if the number is prime
      for (int divisor = 2; divisor <= number/2; divisor++)
      {
        if (number % divisor == 0) // If true, the number is prime
        {
          isPrime = false;
          break;  // Exit the for loop
        }
      }

      // Print the prime number and increase the count
      if (isPrime)
      {
        if (count%10 == 0)
        {
          // Print the number and advance to the new line
          System.out.println(number);
        }
        else
          System.out.print(number + " ");

        count++;  // Increase the count
      }

      // Check if the next number is prime
      number++;
    }
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -