【发布时间】:2018-10-23 11:59:01
【问题描述】:
我有一个我被困在的硬件任务: 我需要编写从 1 到 N 给定种子的序列。 例如: 如果用户输入 4 v 那么我需要写下从第一个序列到第四个序列的每一行,然后写下最后有多少达到 1 并计算数字的数量。 示例:
1 4 2 1 (4)
2 1 (2)
3 10 5 16 8 4 2 1 (8)
4 2 1 (3)
s.o.p :The first 4 hailstone sequences reached 1.
如果用户输入 7 c 那么我只需要写句子 The first 4 hailstone sequences达到1。
到目前为止,我已经编写了 v 部分的代码, 起作用的部分: 公共类 Collatz {
public static void main(String[] args){
int n = Integer.parseInt(args[0]);
String str = String.valueOf(args[1]);
int counter = 1;
if (str.equals("v")) {
while (n != 1)
{
System.out.print(n + " ");
// If n is odd
if ((n & 1) == 1) {
n = 3 * n + 1;
}
// If even
else{
n = n / 2;
}
counter++;
}
// Print 1 at the end
System.out.print(n + " (" + counter + ")");
}
}
}
我尝试使用 for 循环从 1 打印到 n 以便像我的示例一样打印,但它没有,我的尝试:
` for (int i = 1; i < n; i = i+1){
while (i!= 1) {
System.out.print(i + " ");
// If n is odd
if ((i & 1) == 1)
i = 3 * i + 1;
// If even
else
i = i / 2;
}
// Print 1 at the end
System.out.print(i); `
不行。请帮我调试一下。
【问题讨论】:
-
有什么问题?这还不清楚。而且您对
&的使用似乎很奇怪。我很确定应该是%。 -
@Carcigenicate
(n & 1) == 1是使用按位算术对整数进行快速奇数测试(避免昂贵的除法) -
@GyroGearless 啊,对我来说是新的。我一直只使用模数。以前从未在性能敏感的环境中使用它。