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

📄 tryprimesoutput.java

📁 Java Classic Examples是我买的两本书:《JAVA经典实例》和《java入门经典源代码》里边附送光盘里带的源码
💻 JAVA
字号:
import java.io.*;

public class TryPrimesOutput
{
  public static void main(String[] args)
  {
    FormattedInput keyboard = new FormattedInput(); // Keyboard stream 

    System.out.print("Enter the number of primes required: ");

    int numPrimes = keyboard.intRead();  // Number of primes wanted
    long[] primes = new long[numPrimes]; // Array to store primes
    primes[0] = 2;                       // Seed the first prime
    primes[1] = 3;                       // and the second
    int count = 2;                       // count of primes found so far

    long number = 5;                     // Next integer to be tested

    outer:
    for( ; count < primes.length; number += 2L)
    {
      // The maximum divisor we need to try is square root of number
      long limit = (long)Math.ceil(Math.sqrt((double)number));

      // Divide by all the primes we have up to limit
      for(int i = 1; i < count && primes[i] <= limit; i++)
        if(number%primes[i] == 0)        // Is it an exact divisor?
          continue outer;                // yes, try the next number

      primes[count++] = number;          // We got one!
    }

    // Write the primes to a file
    try
    {
      String dirName = "c:\\JunkData";   // Directory for the file
      String fileName = "Primes.bin";    // The file name

      File myPrimeDir = new File(dirName);      // Define directory object

      if(!myPrimeDir.exists())           // If directory does not exist
        myPrimeDir.mkdir();              // ...create it
      else
        if(!myPrimeDir.isDirectory())    // Verify it is a directory
        { // It is not
          System.err.println(dirName+" is not a directory");
          return;
        }

      // Create the file object
      File primesFile = new File(myPrimeDir, fileName); 
      primesFile.createNewFile();        // If it doesn't exist, create it

      // Create a buffered data output stream for the file
      DataOutputStream primesStream = new DataOutputStream(
                new BufferedOutputStream(new FileOutputStream(primesFile)));

      // Write primes to the file
      for(int i = 0; i < primes.length; i++)
        primesStream.writeLong(primes[i]);

      primesStream.close();              // Flush and close the file
      System.out.println("File size = " + primesStream.size());
    }
    catch(IOException e)                 // Catch any output errors
    {
      System.out.println("IOException " + e + " occurred");
    }
  }
}

⌨️ 快捷键说明

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