Here's a program I've written to find prime numbers till a given range and prints them all out to a text file.
I've finished the part where you find the prime numbers but i need help with printing them to the textfile, I'm not really fluent in that area of conding at all.
Thank you.
Sincerely,
Andrew
Code:
import java.math.BigInteger;
import java.io.*;
import java.util.Scanner;
public class PrimeLister
{
private static BigInteger two=new BigInteger("2");
private static BigInteger three=new BigInteger("3");
public static boolean isPrime(BigInteger n)
{
if(n.compareTo(BigInteger.ONE)==0 || n.compareTo(two)==0)
{
return true;
}
BigInteger half=n.divide(two);
for(BigInteger i=three; i.compareTo(half)<=0;i=i.add(two))
{
if(n.mod(i).equals(BigInteger.ZERO))
{
return false;
}
}
return true;
}
public static void write (BigInteger a) throws FileNotFoundException
{
String filename = "output.txt";
PrintWriter pw = new PrintWriter (filename);
byte b = 1;
OutputStream.write (b);
OutputStream.close();
}
public static void main (String args[]) throws IOException
{
PrimeLister pl = new PrimeLister();
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
String prompt = ">";
BigInteger num = BigInteger.valueOf (2);
System.out.println ("Enter Max Limit");
System.out.print (prompt);
int max = Integer.parseInt(br.readLine());
while (num.equals(BigInteger.valueOf(max))!=true)
{
if(pl.isPrime(num))
pl.write(num);
num= num.add (BigInteger.valueOf(1));
}
}
}
Thank you.
Sincerely,
Andrew