我是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;
}
}
答案 0 :(得分:3)
乘法(a * b)
正在以整数乘法的形式完成,导致整数溢出。
要成为双倍乘法,它应该是
...
if(a < N - b)
tot += (a + 1.0) / ((double)a * b);
else
tot += (N - b + 1.0) / ((double)a * b);
...