冰雹序列(Java)

时间:2014-03-29 19:54:05

标签: java

所以我有这个问题分配给我,你写了一个程序,要求一个起始整数和一个结束整数,并返回最长hailstone sequence的长度,开始和结束之间的数字它发生的地方,以及实际的顺序。

我想出了大部分内容,但我仍然坚持打印出实际最大的序列。如果有人可以帮助我,这将真的有帮助。谢谢!

import java.util.Scanner;

public class Hailstone
{


public static void main(String[] args)
{
    Scanner scan = new Scanner(System.in);
    int first, last, counter = -500, highestSequence = 0, highestNumber = 0, number = 0, sequence = 0;

    System.out.println("First candidate?");
    first = scan.nextInt();

    System.out.println("Last candidate?");
    last = scan.nextInt();

        for(int x = first; x <= last; x++)
        {
            number = x;
            counter = 1;

            while(number !=1)
            {
                if(number % 2 == 0) //even
                {
                    number = number/2;
                }
                else //odd
                {
                    number = number*3 + 1;
                }

            counter++; //counts sequence
            }
            if(counter > highestSequence)
            {
                highestSequence = counter;
                highestNumber = x;

                sequence = number; 
            }

        }
        System.out.println("longest sequence of " + highestSequence + " occurs at " + highestNumber);

    }
}

1 个答案:

答案 0 :(得分:2)

您可以简单地使用highestNumber并运行计算序列的代码来打印它。如果您将代码提取到单独的方法(只是草图,验证并自己修改),它将会有所帮助:

   public int checkSequence(int x, boolean print) {
        int number = x;
        while(number !=1)
        {
            if (print) {
               System.out.print(number + " ");
            }
            if(number % 2 == 0) //even
            {
                number = number/2;
            }
            else //odd
            {
                number = number*3 + 1;
            }

        counter++; //counts sequence
        }
        return counter;
   }

在您的计划中,您将致电checkSequence(x, false),在您完成后,您将致电checkSequence(highestNumber, true)