我用 Java 编写了一个程序,但它的计算时间很长,我不知道为什么。有人可以提供一些指示以降低复杂性吗?同样在计算一些值之后,比如在 3,100 之后,它会给出空指针异常。代码:
public class Fraction
{
long n;
long d;
public Fraction()
{
n= 0L;
d= 1L;
}
public Fraction(long a,long b)
{
n= a;
d= b;
}
public Fraction mult(Fraction a, Fraction b)
{
Fraction product = new Fraction();
product.n = a.n * b.n;
product.d = a.d * b.d;
long hcf=gcd(product.n,product.d);
product.n/=hcf;
product.d/=hcf;
return product;
}
public Fraction add(Fraction a, Fraction b)
{
Fraction sum = new Fraction();
sum.d = a.d * b.d;
sum.n = a.n * b.d + a.d * b.n;
long hcf=gcd(sum.n,sum.d);
sum.n/=hcf;
sum.d/=hcf;
return sum;
}
public Fraction divide(Fraction a, Fraction b)
{
Fraction quotient = new Fraction();
quotient.n = a.n * b.d;
quotient.d = a.d * b.n;
long hcf=gcd(quotient.n,quotient.d);
quotient.n/=hcf;
quotient.d/=hcf;
return quotient;
}
long gcd(long a,long b)
{
long hcf=0,min;
min=(a<b)?a:b;
for(long i=1;i<=min;i++)
{
if(a%i==0 &&b%i==0)
hcf=i;
}
return hcf;
}
}
class foo extends Fraction
{
static void main()
{
Fraction obj=new Fraction();
Fraction f[][]=new Fraction[103][103];
for(int i=1;i<=100;i++)
{
f[1][i]=new Fraction(1L,(long)i);
f[i][1]=f[1][i];
f[2][i]=obj.add(new Fraction(1L,(2L*i)),new Fraction((i*i-1L),3L));
f[i][2]=f[2][i];
}
for(int i=3;i<=100;i++)
{
for(int j=1;j<=100;j++)
{
f[i][j+1]=obj.divide(obj.add(new Fraction(1,1),obj.mult(f[i-1][j+1],f[i][j])), f[i-1][j]);
System.out.println(i+","+j+"="+f[i][j].n+"/"+f[i][j].d);
}
}
}
}