In JAVA programming PLEASE answer this question All prime nu
In JAVA programming PLEASE answer this question:
(All prime numbers up to 10,000,000,000 ) Write a program that finds
all prime numbers up to 10,000,000,000 . There are approximately
455,052,511 such prime numbers. Your program should meet the following requirements:
Your program should store the prime numbers in a binary data file, named
PrimeNumbers.dat . When a new prime number is found, the number is
appended to the file.
To find whether a new number is prime, your program should load the
prime numbers from the file to an array of the long type of size 10000 .
If no number in the array is a divisor for the new number, continue to read
the next 10000 prime numbers from the data file, until a divisor is found
or all numbers in the file are read. If no divisor is found, the new number
is prime.
Since this program takes a long time to finish, you should run it as a batch
job from a UNIX machine. If the machine is shut down and rebooted, your
program should resume by using the prime numbers stored in the binary data
file rather than start over from scratch.
Solution
Hey heres the code, I have used DataInputStream and DataOutputStream packages in the program. So when you directly open primedat.txt it will show you some different symbols and not real numbers but when you read from the file using DataInputStream you will be able to see all the numbers so to see the content you have to execute using JVM. If you are not okay with this method post comments I will try other method, if you want you can explain me how exactly you want the program to work.
SourceCode:
import java.io.*;
public class FileDemo {
public static void main(String[] args) throws IOException {
InputStream is = null;
DataInputStream dis = null;
FileOutputStream fos = null;
DataOutputStream dos = null;
long array[]=new long[10000];
int i=0;
try{
fos = new FileOutputStream(\"primedat.txt\");
dos = new DataOutputStream(fos);
dos.writeInt(2);
// force data to the underlying file output stream
dos.flush();
// create file input stream
is = new FileInputStream(\"primedat.txt\");
// create new data input stream
dis = new DataInputStream(is);
// available stream to be read
while(dis.available()>0)
{
// read four bytes from data input, return int
int k = dis.readInt();
array[i]=k;
i++;
}
for(int k=3;k<1000;k++)
{
int flag=0;
for(int l=0;l<i;l++)
{
if(k%array[l]==0)
{
flag=1;
break;
}
}
if(flag==0)
{
System.out.println(k);
dos.writeInt(k);
dos.flush();
array[i]=k;
i++;
}
}
}
catch(Exception e){
// if any error occurs
e.printStackTrace();
}finally{
// releases all system resources from the streams
if(is!=null)
is.close();
if(dis!=null)
dis.close();
if(fos!=null)
fos.close();
if(dos!=null)
dos.close();
}
}
}
Output:
For this program I have placed System.out.println() inside \'for\' loop relating to primes so it will print those primes. You can keep this loop running for upto 10,000,000,000.


