我对 Java 还很陌生,我写了一个方法,double farey_S(int N)
它可以工作到 N = 10,000,但是在 N = 100,000 时它返回一个负数,就好像它溢出了一样。但从输出模式来看:
farey_S(10) = 6.914682539682538
farey_S(100) = 58.296238062166246
farey_S(1000) = 517.9547174126604
farey_S(10000) = 5030.839940050789
farey_S(100000) = -8366.231603179493
输出不应大到足以超过允许的最大值。
这是代码:
public class InverseCoprimeSum {
public static void main(String[] args) {
System.out.println("farey_S(10) = " + farey_S(10));
System.out.println("farey_S(100) = " + farey_S(100));
System.out.println("farey_S(1000) = " + farey_S(1000));
System.out.println("farey_S(10000) = " + farey_S(10000));
System.out.println("farey_S(100000) = " + farey_S(100000));
}
public static double farey_S(int N) {
double tot = 0.0;
int a, b, a1, b1, c, d, k;
a = 0;
b = 1;
c = 1;
d = N;
while(c < N) {
k = (N + b) / d;
a1 = a;
b1 = b;
a = c;
b = d;
c = k * c - a1;
d = k * d - b1;
if(a < N - b)
tot += (a + 1.0) / (a * b);
else
tot += (N - b + 1.0) / (a * b);
}
tot -= 2;
return tot;
}
}