Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

The Hailstone program reads in an int then computes and prints the hailstone sequence for that number. It also prints the length of the sequence,

The Hailstone program reads in an int then computes and prints the hailstone sequence for that number. It also prints the length of the sequence, the largest number in the sequence, the longest sequence from one to the number and the number that has the longest sequences from on to the number. I have everything correct except for the function startNum(int n) that is supposed to return the number that has the longest hailstone sequences from one to that number "n". i get a stackoverflow error

public class Recursion {

public static void main(String[] args) {

hailstoneSeq(16); System.out.println(" "+hailstoneLen(16));

System.out.println(largestValue(16));

System.out.println(longLength(16));

System.out.println(startNum(16)); }

public static int next(int n) {

if (n % 2 == 0){

return n / 2; }

else if (n % 2 != 0 && n != 1)

{ return (3 * n) + 1;

} return n;

}

public static void hailstoneSeq(int n)

{

int val = n;

if (val == 1)

System.out.print(val);

else

{ System.out.print(val + " "); hailstoneSeq(next(val));

}

} public static int hailstoneLen(int n) {

if (n == 1)

{ return n;

} else {

return 1 + hailstoneLen(next(n)); }

}

public static int largestValue(int n)

{ if (n == 1) {

return n;

} else

{

return Math.max(n,largestValue(next(n)));

}

}

public static int longLength(int n)

{

if (n == 1)

{

return n;

}

else

{

return Math.max(hailstoneLen(n), Math.max(hailstoneLen(n-1), longLength(n-1)));

}

}

public static int startNum(int n)

{

int val; if (n == 1)

{

return n;

} else

{ val = n--; Math.max(hailstoneLen(n), Math.max(hailstoneLen(n-1), startNum(n-1))); return val;

}

}

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Beginning ASP.NET 2.0 And Databases

Authors: John Kauffman, Bradley Millington

1st Edition

0471781347, 978-0471781349

More Books

Students also viewed these Databases questions