The Collatz conjecture states if you pick a positive integer

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

Solution

// 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

*/

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 a
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 a

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site