【问题标题】:Trying to print out only the prime numbers into an output file尝试仅将素数打印到输出文件中
【发布时间】:2018-10-31 17:10:20
【问题描述】:

我必须创建一个包含一串数字的输入文件。我需要我的程序来创建一个输出文件,其中只有输入文件的质数。我完全不知道如何创建一个循环来检查我的输入文件中的素数并创建一个只有素数的输出文件。

import java.util.Scanner;
import java.io.*;


public class ClassWork5_3 
{


    public static void main(String[] args) throws IOException 
    {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter file name: ");
        String filename = keyboard.nextLine();
        PrintWriter pw = new PrintWriter("output.txt");

        File file = new File(filename);
        Scanner inputFile = new Scanner(file);
        int line = inputFile.nextInt();


       while(inputFile.hasNext())
       {
         isPrime(line);

       }

    }

    public static boolean isPrime(int num)
    {
        boolean status;
        for(int i = 2; i < num/2; i++)
        {
            if (num%i==0)
            {
             status = false;
            }

        }
        return true;
    }   
}

【问题讨论】:

  • 你想从控制台或文件中读取输入数字吗?
  • 我希望程序从我创建的输入文件中读取数字,然后将素数写入自己的输出文件中。
  • 你的方法是正确的,只是你需要将输出发送到文件,如果返回的状态为真,则需要添加 pw.write(line) 类似的东西
  • 而您忘记在 while 循环中添加 line=inputFile.nextInt() 这是您无法获得结果的主要原因
  • 我更新了我的代码,但我不知道如何将它发布到这里查看。它现在仍然在我的输出文件中为我提供与输入文件相同的数字,包括素数和非素数。

标签: java primes


【解决方案1】:

首先,你的方法isPrime()不正确。
这个应该可以工作,尽管它可能不是最有效的:

public static boolean isPrime(int n)
{
  // Manage easy cases
  if (n <= 1)
    return (false);
  else if (n == 2)
    return (true);
  else if ((n % 2) == 0)
    return (false);

  // Check if (odd) number can be divided by something
  for (int i = 3; i <= n / 2; i += 2)
  {
    if ((num % i) == 0)
      return (false);
  }

  // If we get here, we got a prime number
  return (true);

} // isPrime

那么,你的while 循环应该是这样的:

while(inputFile.hasNext())
{
  line = inputFile.nextInt();
  if (isPrime(line))
    pw.println(line);
}

【讨论】:

  • 你知道2 是质数,但所有其他偶数都不是
  • @forpas 抱歉,我把支票倒过来了。更新了答案
  • 不要忘记阅读 while 循环中的下一行。所以你应该添加语句“line = inputFile.nextInt”
  • @WalaSaif 我快速输入了答案。现在更新了。
【解决方案2】:

此方法遍历nMath.sqrt(n) 的可能除数:

public static boolean isPrime(int n) {
    if (n < 2)
        return false;
    else if (n <= 3 )
        return true;

    boolean notPrime = true;

    for (int divisor = 2; divisor <= Math.sqrt(n); divisor++) {
        notPrime = (n % divisor == 0);
        if (notPrime)
            break;
    }

    return !notPrime;
}

【讨论】:

    【解决方案3】:

    这是使用 while 循环和 Math.sqrt() 的另一种可能的解决方案:

    public class X1 {
    
    public static void main(String[] args) {
        File inputFile = null;
        Scanner fileInput = null;
        PrintStream fileOutput = null;
    
        try {
            inputFile = new File("input.txt");
            fileInput = new Scanner(inputFile, "UTF-8");
            fileOutput = new PrintStream("output.txt", "UTF-8");
    
            while (fileInput.hasNext()) {
                int number = fileInput.nextInt();
                if (isPrime(number))
                    fileOutput.println(number);
            }
    
        } catch (FileNotFoundException fnfe) {
            System.out.println("File not found!");
        } catch (UnsupportedEncodingException uee) {
            System.out.println("Unsupported encoding!");
        } finally {
            if (fileInput != null) {
                fileInput.close();
            }
            if (fileOutput != null) {
                fileOutput.close();
            }
        }
    
    }
    
    private static boolean isPrime(int n) {
        int divider = 2;
        boolean prime = true;
        while (prime && (divider <= (int) Math.sqrt(n))) {
            if (n % divider == 0) {
                prime = false;
            }
            divider++;
        }
        return prime;
    }
    

    }

    【讨论】:

      【解决方案4】:

      代码是针对C++的,但是算法是一样的。

      bool IsPrime(unsigned int num)
      {
          // 2 is the first prime number; 
          if(num < 2) return false;
      
          // We check dividers up to the root of the given number,
          //because after that the multipliers are the same, but with switched places. 
          //Example: 12 = 1*12 = 2*6 = 3*4 = 4*3 = 6*2 = 12*1
          unsigned int limit = sqrt(num);
      
          //We calculated the limit outside the loop so it's calculated only once
          //instead of being calculated at every iteration of the loop.
          for(unsigned int i=2; i < limit; ++i)
          {
              //If we divide without a remainder, then it's not prime.
              if(num%i==0)
                  return false;
          }
      
          //We have tried with all the possible multipliers and have found no dividers.
          return true;
      }
      

      【讨论】:

        猜你喜欢
        • 2011-12-19
        • 1970-01-01
        • 2022-01-17
        • 1970-01-01
        • 2018-09-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多