试图制作一个简单的程序来测试Collat​​z猜想中的数字

时间:2016-09-25 03:53:07

标签: java

我只想说这是一个编码菜鸟。这可能是我编写的最高级代码。

我正在尝试在Collat​​z猜想中测试数字。在循环变为1之后,我的输入变量应该增加1.如果它不是1,那么它将转到其他2个函数。如果数字是偶数,则除以2.如果是奇数,则将其乘以3并加1。

这个数学方程式如此有趣的原因是我们不知道所有数字是否在给定的时间内得到足够多的数字。

我也知道没有休息;在循环中,但这不是问题。我的问题是输出。这是我的代码:

public class class1 {

static int output = 0;
static int input = 1;
static int turn = 0;

public static void main(String[] args) {
    output = input;
    for (;;) {
        if(input != 1){
            if (input % 2 == 0) {
                even(input);
                System.out.println("output = " + input + " turn = " + turn);
            } else if (input % 2 == 1) {
                odd(input);
                System.out.println("output = " + input + " turn = " + turn);
            }
        }else{
            System.out.println("done in " + turn + " turns");
            turnsTested++;
            turn = 0;
            output = input;
        }
        turn++;
    }
}//end main


public static int even(int input2) {
    input = input / 2;
    return input;

}

public static int odd(int input2) {
    input = (input * 3);
    input++;
    return input;
     }
}//end class

以下代码运行的输出:

output = 2734 turn = 105

output = 1367 turn = 106

output = 4102 turn = 107

output = 2051 turn = 108

output = 6154 turn = 109

output = 3077 turn = 110

output = 9232 turn = 111

output = 4616 turn = 112

output = 2308 turn = 113

output = 1154 turn = 114

output = 577 turn = 115

output = 1732 turn = 116

output = 866 turn = 117

output = 433 turn = 118

output = 1300 turn = 119

output = 650 turn = 120

output = 325 turn = 121

output = 976 turn = 122

output = 488 turn = 123

output = 244 turn = 124

output = 122 turn = 125

output = 61 turn = 126

output = 184 turn = 127

output = 92 turn = 128

output = 46 turn = 129

output = 23 turn = 130

output = 70 turn = 131

output = 35 turn = 132

output = 106 turn = 133

output = 53 turn = 134

output = 160 turn = 135

output = 80 turn = 136

output = 40 turn = 137

output = 20 turn = 138

output = 10 turn = 139

output = 5 turn = 140

output = 16 turn = 141

output = 8 turn = 142

output = 4 turn = 143

output = 2 turn = 144

output = 1 turn = 145

done in 146 turns

所以我有一个错误。我无法找到问题所在。

1 个答案:

答案 0 :(得分:0)

        if (input % 2 == 0) {
            // transforming a primitive method argument in a function is
            // *NOT* reflected on the variable passed as argument:
            // a call to the function will pass *the value* of the variable 
            // and not the reference to the variable
            input = even(input);
            System.out.println("output = " + input + " turn = " + turn);
        } else if (input % 2 == 1) {
            // see above
            input = odd(input);
            System.out.println("output = " + input + " turn = " + turn);
        }