Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The Collatz conjecture states: if you pick a positive integer value of one or gr

ID: 3935490 • Letter: T

Question

The Collatz conjecture states: if you pick a positive integer value of one or greater and if it is even divide it by two if it is odd multiply it by three and add one and you repeat this procedure long enough on each resulting value, eventually you will reach the value one. Write a recursive method int Collatz(int) in Java that computes the Collatz conjecture value by calling itself for each next value in the sequence. Then, devise a way to keep track of how many times the method is called before it ends and returns the value 1. Finally, add code to call your method

Explanation / Answer

// CollatzConjecture.java

import java.util.Scanner;

public class CollatzConjecture
{
public static int recursiveCall = 0;

public static void collatz(int n)
{
System.out.println(n + " ");
if (n == 1) return;
else if (n % 2 == 0)
{
recursiveCall++;
System.out.println("Recursive call");
collatz(n / 2);
}
else collatz(3*n + 1);
}

public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.print("Enter a number: ");
int n=sc.nextInt();

collatz(n);
System.out.println(" Number of times the method is called before it ends and returns the value 1: " + recursiveCall);
}

}

/*
output:

Enter a number: 25

25
76
Recursive call
38
Recursive call
19
58
Recursive call
29
88
Recursive call
44
Recursive call
22
Recursive call
11
34
Recursive call
17
52
Recursive call
26
Recursive call
13
40
Recursive call
20
Recursive call
10
Recursive call
5
16
Recursive call
8
Recursive call
4
Recursive call
2
Recursive call
1

Number of times the method is called before it ends and returns the value 1: 16

*/

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote