Cod*_*lus 0 java reference function parameter-passing
在函数中fermatFactorization(),a并且b作为参考参数传递,因为我使用的是LongClass.然而,在功能上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);
}
Run Code Online (Sandbox Code Playgroud)
Java是按值传递的.如果为参数指定新值,则不会影响调用方法中的值.
您有两种选择:
让你的方法的返回a和b-无论是在int[]或使用单独的FactorizationRezult有两个领域类.这样,您将在被调用方法中声明a和b作为局部变量,而不是将它们作为参数.这是最明智的方法.
另一种方法是使用a MutableLong并使用setValue(..)方法 - 这样更改将影响调用方法中的对象.这是不太可取的