在函数 fermatFactorization()
中, a
和b
被作为引用参数传递,因为我使用的是 Long
类(class)。然而,在函数 testFermatFactorization()
中当我经过a
时和b
至fermatFactorization()
, a
的值和b
不改变,所以testFermatFactorization()
打印(0)(0)
。我通过打印 a
来测试这一点和b
在fermatFactorization()
,我得到了我期望的输出。
我忽略了什么?编译器可以改变 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);
}
最佳答案
Java 是按值传递的。如果为参数分配新值,它不会影响调用方方法中的值。
您有两个选择:
使您的方法返回
a
和b
- 在int[]
中或使用单独的FactorizationRezult
有两个字段的类。这样,您将在调用的方法中将a
和b
声明为局部变量,而不是将它们作为参数。这是最可取的方法。另一种方法是使用
MutableLong
并使用setValue(..)
方法 - 这样更改将影响调用方方法中的对象。这是不太可取的
关于Java 按引用传递和编译器优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12698414/