最近看 java 的时候,碰到了一个问题,代码如下:
package com.company;
import java.util.Random;
public class Main {
final static int MAX = 100;
final static int MIN = 10;
public static int gcd(int p, int q) {
return (q == 0) ? p : gcd(q, p % q);
}
public static void main(String[] args) {
// write your code here
int p, q;
Random r = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
p = r.nextInt(MAX) % (MAX - MIN + 1) + MIN;
q = r.nextInt(MAX) % (MAX - MIN + 1) + MIN;
while (p == q) {
System.out.println("hit - " + p + ", " + q);
q = r.nextInt(MAX) % (MAX - MIN + 1) + MIN;
}
sb.append("GCD of " + p + " and " + q + " is " + gcd(p, q));
sb.append(System.getProperty("line.separator"));
}
System.out.println(sb);
return;
}
}
输出结果是:
hit - 15, 15
GCD of 31 and 30 is 1
GCD of 15 and 48 is 3
GCD of 78 and 44 is 2
GCD of 89 and 18 is 1
GCD of 60 and 17 is 1
GCD of 86 and 59 is 1
GCD of 73 and 18 is 1
GCD of 22 and 84 is 2
GCD of 75 and 66 is 3
GCD of 99 and 46 is 1
这里有一个问题,我本来的意思是,当 q 取到与 p 一样的随机值时,重取一次,直到与 p 不一致为止.在实际代码运行中,当 p 为 15 的时候,p 应该不重新取值,q 重新取值,第一次 hit 的时候,p 应该是保持 15,而 q 是新的随机值.但是执行结果却不是这样的,请问一下问题出在哪里?
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.