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

📄 primesfile.java

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

public class PrimesFile
{
  static RandomAccessFile myFile = null;   // File stream
  static boolean file = false;             // True if file contains primes
  static long[] primes = new long[10];     // Array to store primes
  static int current = 0;                  // Free element in primes array
  final static int LONGSIZE = 8;           // Number of bytes for type long

  // The main computation
  public static void main(String[] args)
  {
    try
    {
      // Define the file to store primes
      File myPrimes = new File("c:\\JunkData\\Primes.bin");
      myFile = new RandomAccessFile(myPrimes, "rw");

      // Read the number of primes required
      FormattedInput in = new FormattedInput();   // Keyboard stream

      // Prompt for keyboard input
      System.out.print("Enter the number of primes required: ");
      int numPrimes = in.intRead();               // Number of primes required

      long count = myFile.length()/LONGSIZE;      // Number of primes in the file
      long number = 0;                            // Next number to be tested

      // Check for file contents
      if(count == 0)               // Nothing in the file
      {
        file = false;
        primes[0] = 2;             // Seed the first prime...
        primes[1] = 3;             // ...and the second
        current = 2;               // Index of next element
        count = 2;                 // count of primes found - up to now
        number = 5;                // Next integer to be tested
      }
      else
      {       // Get the next number to test - the last prime + 2
        file = true;
        myFile.seek(myFile.length() - LONGSIZE);
        number = myFile.readLong() + 2;
      }

      // Find additional primes required for the total primes requested
      for( ; count < numPrimes; number += 2)
      {
        if(primeTest(number))                 // Test for a prime
        {
          primes[current++] = number;         // We got one!
          ++count;                            // Increment prime count

          if(current == primes.length)        // Check for array full
          {// Array is full so write them away
            myFile.seek(myFile.length());     // Go to the end of the file
            for(int i = 0; i < primes.length; i++)
              myFile.writeLong(primes[i]);    // Write the primes
            current = 0;                      // Set free array element index
            file = true;                      // Indicate file has primes
          }
        }
      } 

      // Check if there are still primes in the array
      if(current > 0)
      { // There are - so write them to the file
        myFile.seek(myFile.length());         // Go to the end of the file
        for(int i = 0; i < current ; i++)
          myFile.writeLong(primes[i]);        // Write the primes
        current = 0;                          // Set free array element index
        file = true;                          // Indicate file has primes
      }
      outputPrimes(numPrimes);                // Output the primes 
    }
    catch(IOException e)
    {
      System.err.println("Error in main()\n" + e);   // Output the error
    }
  }

  // Test whether a number is prime
  static boolean primeTest(long number)
  {
    // The maximum divisor we need to try is the square root of number
    long limit = (long)Math.ceil(Math.sqrt((double)number));
    try
    {
      if(file)                          // Check whether we have primes on file...
      {                                 // Yes, we do
        long prime = 0;                               // Stores prime from file
        myFile.seek(0);                               // Go to file start
        long primeCount = myFile.length()/LONGSIZE;   // Number of primes on file

        // Check the number using the primes from file
        for(int i = 0; i < primeCount; i++)
        {
          prime = myFile.readLong();                  // Read a prime
          if(prime > limit)
            return true;             // No exact division - prime found
          if(number%prime == 0)
            return false;            // Exact division - not a prime
        }
      }
    }
    catch(IOException e)                           // Handle read error
    { // Exception thrown - output message
      System.err.println("Error in primeTest():\n" + e); 
      System.exit(1);                              // End the program
    }

    // Otherwise check using primes in memory
    for(int i = 0; i < current; i++)
    {
      if(primes[i] > limit)
        return true;               // No exact division - prime found
      if(number%primes[i] == 0)
        return false;              // Exact division - not a prime
    }
    return true;
  }

  // Method to display primes
  static void outputPrimes(int numPrimes) throws IOException
  {
    // Create a buffered formatted output stream
    FormatWriter out = new FormatWriter(
                         new BufferedWriter(
                         new FileWriter(FileDescriptor.out)), true, 12);

    myFile.seek(0);                        // Go to file start
    for(int i = 0; i < numPrimes; i++)     // Output the primes
    {
      long prime = myFile.readLong();      // Read a prime from the file

      if(i%5 == 0)
        out.println();                     // After every 5th, a newline

      out.print(prime);                    // Output the prime
    }
    out.close();                           // Close the stream
  }
}

⌨️ 快捷键说明

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