Background The game 3N 1 has the following rules If N is od

Background: The game \"3N + 1\" has the following rules: If N is odd, multiply it by 3 and add 1. If N is even, divide it by 2. Repeat until N equals 1. Every value of N that anyone has ever checked eventually leads to 1, but it is an open mathematical problem (known as the Collatz conjecture) whether EVERY value of N eventually leads to 1. You can also read about this problem on Wikipedia. Before you start working on this program, take a sheet of paper and write out what happens when you start with N = 5, N = 6, N = 7, N = 9, to get a feel for how the game works. For example, starting with N = 6, the next number is 3, then 10, then 5, then 16, 8, 4, 2, 1 and then we are done. Create a class named Problem2 that contains the main method. For now, leave the main method empty (no code). Create another method named threeNPlusOne that takes one parameter, an integer named n. The method should not return anything (void). Use the method parameter and write the code to play the game for any integer n. Keep track of the maximum value that occurs after each modification (include the original value of n) and the number of times that you have modified n since its original value. After reaching 1, print out the original value of n, the maximum value, and the number of times n was modified. Several sample method calls have been provided for you below. Test your method by calling it in the main method using the sample method calls. Your output must match the sample output format exactly. Put the Problem2.java file in the Homework6 folder to be submitted to D2L.

Solution

Solution:

public class Problem2
{
public static void main(String args[])
{
   //method calling
threeNPlus(6);
threeNPlus(31);
threeNPlus(78);
}
public static void threeNPlus(int n)
{
   //method definition
   int max=n,count=0;
   System.out.println(\"Original \"+n);
   while(n>1)
   {
   if(n%2==0)
       n/=2;
   else
       n=n*3+1;
if(n>max)
   max=n;
count++;
   }
   System.out.println(\"Maximum \"+max);
   System.out.println(\"Count \"+count);
}  
}

Output:

Original 6
Maximum 16
Count 8
Original 31
Maximum 9232
Count 106
Original 78
Maximum 304
Count 35

 Background: The game \

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site