如何在Java中只使用2个变量,就像Python代码一样?

huangapple go评论80阅读模式
英文:

How can I only use 2 variables in Java as with the Python code?

问题

这是相同功能的Java代码:

private static int gcd(int a, int b) {
    // 使用欧几里德算法返回最大公约数。
    while (b != 0) {
        a = a % b;
        // 交换a和b的值,以继续迭代。
        int temp = a;
        a = b;
        b = temp;
    }
    return a;
}

System.out.println(gcd(210, 45));

这个Java代码只使用了两个变量,与Python代码相似。Java需要一个额外的变量来交换a和b的值,因为没有元组的概念,所以需要一个额外的变量来完成值的交换。

英文:

Can this Python code also be written in Java code? :

def gcd(a, b):
    # Return greatest common divisor using Euclid's Algorithm.
    while b:
        a, b = b, a % b
    return a

print (gcd(210, 45))

This is what I've so far in Java code:

private static int gcd(int p, int q) {
    // Return greatest common divisor using Euclid's Algorithm.
    int temp;
    while (q != 0) {
        temp = q;
        q = p % q;
        p = temp;
    }
    return p;
}

System.out.println(gcd(210, 45));

As you can see the Java code uses 3 variables whereas the Python code only uses 2 variables. I also want to use only 2 variables in the Java code and I want to keep the while loop and I don't want to use recursion.

Also why does Java need 1 more variable than the Python code? Except for the fact that the Python code uses a tuple.

答案1

得分: 2

以下是翻译好的代码部分:

两个变量但你仍然需要交换
public static int gcd(int r, int s) {
    while (s != 0) {
        r %= s;
        // 交换它们
        r ^= s;
        s ^= r;
        r ^= s;
    }
    return r;
}

另一种可能性(但不是Java)是在字节码中编写一个程序,将其存储在byte[]数组中,并将其作为Java方法执行。如果使用内部堆栈与Python一样是可以的,那么在这里也应该可以。

英文:

Two variables but you still have to swap.

public static int gcd(int r, int s) {
	while (s != 0) {
		r %= s;
        // swap them
		r ^= s;
		s ^= r;
		r ^= s;
	}
	return r;
}

Another possibility (but it wouldn't be Java) is to write a routine in byte code, store it in a byte[] array and execute it as a Java method. If using the internal stack is okay as it is in Python, then it should be okay here.

答案2

得分: 1

The reason for the difference is that Python has a tuple creation/decomposition feature, and Java does not.

As other answers have mentioned, you can do an integer swap with either xor or addition/subtraction. However, I suspect that for performance platforms like C or Rust, this is a false economy, and this hack will not speed things up or decrease resource usage. (If you're just in it for the challenge, though, it's legit, and probably the only solution)

Also, I don't think Java permits this trick for more general object references.

英文:

The reason for the difference is that Python has a tuple creation/decomposition feature, and Java does not.

As other answers have mentioned, you can do an integer swap with either xor or addition/subtraction. However, I suspect that for performance platforms like C or Rust, this is a false economy, and this hack will not speed things up or decrease resource usage. (If you're just in it for the challenge, though, it's legit, and probably the only solution)

Also, I don't think Java permits this trick for more general object references.

答案3

得分: 1

在每次循环迭代中执行两个步骤,而不进行任何交换操作,如下所示:

private static int gcd(int p, int q) {
    // 使用欧几里德算法返回最大公约数。
    while (q != 0) {
        p %= q;
        if (p == 0)
           return q;
        q %= p;
    }
    return p;
}
英文:

How about doing two steps in each loop iteration and not swapping at all?

private static int gcd(int p, int q) {
    // Return greatest common divisor using Euclid's Algorithm.
    while (q != 0) {
        p %= q;
        if (p == 0)
           return q;
        q %= p;
    }
    return p;
}

答案4

得分: 0

在Java中,你也可以使用两个变量执行gcd(最大公约数)操作,如果我理解正确的话。

private static int gcd(int p, int q) {
    // 使用欧几里德算法返回最大公约数。
    int temp;
    while (p != q) {
        if (p > q)
            p = p - q;
        else
            q = q - p;
    }
    return q;
}
英文:

Correct me If I'm wrong but, you can also do gcd operation using 2 variables in java.

private static int gcd(int p, int q) {
    // Return greatest common divisor using Euclid's Algorithm.
    int temp;
    while (p != q) {
        if(p > q)
            p = p - q;
        else
            q = q - p;
    }
    return q;
}

答案5

得分: 0

Python 可能会在“异或”运算符之上添加一些合成糖。这是一种位运算,用于交换两个不同变量的值,而不使用临时变量。

请参见下面的Java示例:

a = a^b;
b = a^b;
a = a^b;

详细信息请查看此链接

英文:

Python might be adding some synthetic sugar on top of the "exclusive or" operator. This is a bitwise operation to swap values of two different variables without using a temporary variable.

See Java example below:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-java -->

a = a^b;
b = a^b;
a = a^b;

<!-- end snippet -->

See https://en.wikipedia.org/wiki/XOR_swap_algorithm

答案6

得分: 0

除了给定的例子之外,还有一种众所周知的算法,可以在不使用第三个变量的情况下交换两个整数变量ab

// 给定:两个整数变量 a 和 b
a += b;
b = a - b;
a -= b;
// 结果:a 和 b 已经交换

如果我们现在首先计算a % b并将其赋值给a,那么剩下的就是交换ab了:

// 给定:两个整数变量 a 和 b
a = a % b;
a += b;
b = a - b;
a -= b;
// 结果:a 的新值为 b,而 b 的新值为 a % b

即使加法a + b溢出,这种方法也能正常工作,因为它会被减法反转。


顺便说一句:我将其视为一种代码高尔夫。除非受到严重的内存限制,否则我不建议使用这种解决方案。

英文:

Aside from the given examples, there is a well known algorithm to swap two integer variables a and b without the use of a third variable:

// given: two int-variables a and b
a += b;
b = a - b;
a -= b
// result: a and b have been swapped

If we now first calculate a % b and assign it to a, all that is left to do is to swap a and b:

// given: two int-variables a and b
a = a % b;
a += b;
b = a - b;
a -= b
// result: the new value of a is b, while the new value of b is a % b

This even works if the addition a + b overflows, since it is reversed by the subtractions.


As an aside: I see this as a code golf. Unless one is under heavy memory constraint, I would not advice to use this solution.

huangapple
  • 本文由 发表于 2020年8月1日 04:31:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/63198753.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定