如何在1处停止我的Collat​​z序列码?

时间:2016-12-25 15:28:01

标签: java while-loop collatz

我尝试使用while循环实现Collat​​z序列,但我无法将序列停在1.代码继续。我尝试了所有可能性,但我无法提出解决方案。

import java.util.Scanner;

public class cs{
    public static void main(String[] args)throws Exception{
        System.out.println("Starting number: ");
        Scanner s = new Scanner(System.in);
        int a = s.nextInt();
        System.out.print(" " + a);
        while(a>1)
        {
            if(a == 1) break; // this is not working though
            if((a % 2 ) == 0) {
            a = a / 2;
            System.out.print("  " + a);
            }

            Thread.sleep(1000);
            if((a % 2) != 0){
                a = (a * 3) + 1;
                System.out.print(" " + a);
            }

            Thread.sleep(1000);
        } 
    }
}

4 个答案:

答案 0 :(得分:2)

此处的第二个if条件应为第一个else

if((a%2)==0){
    // ...
}

// ...
if((a%2)!=0){

像这样:

    while (a > 1) {
        if ((a % 2) == 0) {
            a /= 2;
            System.out.print("  " + a);
        } else {
            a = (a * 3) + 1;
            System.out.print("  " + a);
        }
    }

我还删除了if (a == 1)这条毫无意义的行, 由于while (a > 1)条件, if永远不会是true

最后,我建议您更加注意正确缩进代码, 并像我一样在运营商周围添加空间, 否则代码难以阅读,理解和调试。

答案 1 :(得分:1)

问题必须是a永远不等于1.尝试在每个循环中打印a的值,看看它实际上等于:

while(a > 1)
{
    // This line is not required because if a == 1 then the while loop would terminate anyway:
    //  if(a==1) break; //this is not working though

    if((a%2)==0){
        a = a/2;
        System.out.print("  "+a);
    }

    Thread.sleep(1000);

    if((a%2)!=0){
        a = (a*3)+1;;
        System.out.print("  "+a);
    }

    Thread.sleep(1000);

    System.out.println("a = " + a); // This checks what the value of a actually is
} 

答案 2 :(得分:0)

您的循环在Collat​​z序列中执行两个步骤,而不是仅执行一个步骤。即使a1,它也会继续进入第二个if,并将其转为4,因此循环永远不会终止。相反,您应该使用else子句,只需每次循环执行一步:

while (a > 1)  {
    if ((a%2) == 0) {
        a = a / 2;
    } else {
        a = (a * 3) + 1;
    }

    Thread.sleep(1000);
    System.out.print("  " + a);
}

答案 3 :(得分:0)

这足以满足您的需求:

$ python 
Python 2.7.10 (default, Jul 30 2016, 19:40:32) 
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> help(help)
Help on _Helper in module site object:

class _Helper(__builtin__.object)
 |  Define the builtin 'help'.
 |  This is a wrapper around pydoc.help (with a twist).
 |  
 |  Methods defined here:
 |  
 |  __call__(self, *args, **kwds)
 |  
 |  __repr__(self)
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)

因为如果你看一下你的状况,就会发现while (a > 1 && (a % 2) != 0){ a /= 2; System.out.print(" " + a); } 大于1 ==>不能是1,因此,不需要第一个a语句。

所以你的课将如下:

if