尝试仅将质数打印到输出文件中

时间:2018-10-31 17:10:20

标签: java primes

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

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;
    }   
}

4 个答案:

答案 0 :(得分:0)

首先,您的方法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);
}

答案 1 :(得分:0)

此方法迭代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;
}

答案 2 :(得分:0)

这是使用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;
}

}

答案 3 :(得分:0)

代码是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;
}