📄 primesfile.java
字号:
import java.io.*;
public class PrimesFile
{
RandomAccessFile raf;
public static void main(String args[])throws IOException
{
(new PrimesFile()).createprime(100);
}
public void createprime(int max) throws IOException
{
raf=new RandomAccessFile("primes.bin", "rw");
raf.seek(0);
raf.writeInt(2);
int k=3 ;
while(k<=max)
{
if(isPrime(k))
raf.writeInt(k);
k=k+2;
}
output(max);
raf.close();
}
public boolean isPrime(int k)throws IOException
{
int i=0, J ;
boolean yes=true;
try
{
raf.seek(0);
int count=(int)(raf.length()/4);
while((i<=count)&&yes)
{
if(k%raf.readInt()==0)
yes=false ;
else
i++;
raf.seek(i*4);
}
}
catch(EOFException e){}
return yes;
} //方法结束
public void output(int max) throws IOException
{
try
{
raf.seek(0);
System.out.println("[2~"+max+"]中有"+(raf.length()/4)+"个素数:");
for(int i=0;i<(int)(raf.length()/4);i++)
{
raf.seek(i*4);
System.out.print(raf.readInt()+" ");
if ((i+1)%10==0) System.out.println();
}
}
catch(EOFException e){}
System.out.println();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -