【发布时间】:2012-09-23 18:51:59
【问题描述】:
在函数fermatFactorization()、a 和b 中作为参考参数传递,因为我使用的是Long 类。但是,在函数testFermatFactorization() 中,当我将a 和b 传递给fermatFactorization() 时,a 和b 的值不会改变,所以testFermatFactorization() 打印(0)(0)。我通过在fermatFactorization() 中打印出a 和b 进行了测试,得到了我期望的输出。
我忽略了什么?编译器能否更改fermatFactorization() 中的a 和b,因为它们只是被分配给?(怀疑)
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);
}
【问题讨论】:
-
查看这个关于变异包装类的问题:stackoverflow.com/questions/4117793/…
-
看看我的回答here。它实际上不是通过引用,而是通过引用的值,因此您实际上无法像更改指针那样更改原始引用。
-
如果性能很重要,你应该使用
long而不是Long并且尽可能使用double而不是Double。
标签: java function reference parameter-passing