在函数fermatFactorization()
中,a
和b
正在作为参考参数传递,因为我使用的是Long
类。然而,在功能testFermatFactorization()
当我通过a
和b
到fermatFactorization()
的a
和b
值不得到改变,所以testFermatFactorization()
打印(0)(0)
。我在fermatFactorization()
中打印出a
和b
,并得到了我期望的输出结果。Java通过引用和编译器优化
我在忽略什么?可以在编译器改变a
和b
在fermatFactorization()
,因为它们只被分配到?(可疑)
public static void fermatFactorization(Long n, Long a, Long b)
//PRE: n is the integer to be factored
//POST: a and b will be the factors of n
{
Long v = 1L;
Long x = ((Double)Math.ceil(Math.sqrt(n))).longValue();
//System.out.println("x: " + x);
Long u = 2*x + 1;
Long r = x*x - n;
while(r != 0) //we are looking for the condition x^2 - y^2 - n to be zero
{
while(r>0)
{
r = r - v; //update our condition
v = v + 2; //v keeps track of (y+1)^2 - y^2 = 2y+1, increase the "y"
}
while(r<0)
{
r = r + u;
u = u + 2; //keeps track of (x+1)^2 - x^2 = 2x+1, increases the "x"
}
}
a = (u + v - 2)/2; //remember what u and v equal; --> (2x+1 + 2y+1 - 2)/2 = x+y
b = (u - v)/2; // --> (2x+1 -(2y+1))/2 = x-y
}
public static void testFermatFactorization(Long number)
{
Long a = 0L;
Long b = 0L;
fermatFactorization(number, a, b);
System.out.printf("Fermat Factorization(%d) = (%d)(%d)\n", number, a, b);
}
退房有关变异包装类这样的问题: http://stackoverflow.com/questions/4117793/are-java-wrapper-classes-really-immutable – MikeB
看一看我的答案[这里](HTTP: //stackoverflow.com/questions/12591294/how-can-i-delete-an-object-passed-into-a-java-method/12591366#12591366)。它不是通过引用实际引用,而是引用的_value_,所以实际上不能像更改指针那样更改原始引用。 – Brian
如果性能很重要,你应该使用'long'而不是'Long',如果可以的话,也可以使用'double'而不是'Double'。 –