萌新自己写了一个用链表找质数的代码,运行时没问题,但如果输入的数太大,就会出错,为什么会这样?求大神解答,万分感谢!
代码如下:
//一个找出质数的程序
public class Zhishu{
public static Zhishu firstZhishu=new Zhishu(2);
public Zhishu next=null;
public int number=0;
private Zhishu(int number){
this.number=number;
}
public static void main(String[] args){
Zhishu.find(19);
Zhishu.find(17);
Zhishu.find(100);
Zhishu.find(1000);
Zhishu.find(1069);
Zhishu.find(3630);
Zhishu.find(5000);
}
public static void find(int n){
find(n,firstZhishu);
}
private static void find(int n,Zhishu a){
if (n==a.number){
System.out.println(n+"是质数");
return;
}else if(n<a.number){
System.out.println(n+"不是质数");
return;
}else if(a.next==null){
find(a.number+1,n,a);
}else{
find (n,a.next);
}
}
private static void find(int i,int n,Zhishu a){
if (i<n){
if (test(i,firstZhishu)){
a.next=new Zhishu(i);
find(i+1,n,a.next);
}else{
find(i+1,n,a);
}
}else{
if (test(n,firstZhishu)){
a.next=new Zhishu(n);
System.out.println(n+"是质数");
}else{
System.out.println(n+"不是质数");
}
}
}
private static boolean test(int i,Zhishu a){
if (i%a.number==0){
return false;
}else if(a.number*2>i){
System.out.println("找到质数"+i);
return true;
}else{
return (test(i,a.next));
}
}
}