Core Java

Generating the Juggler Sequence in Java

The Juggler sequence is a mathematical sequence defined for a given non-negative integer a0​. This sequence is generated by repeatedly applying a specific formula until we reach 1. In this article, we will delve into how we can implement the Juggler sequence generation in Java.

1. Understanding the Juggler Sequence

The Juggler sequence is a mathematical sequence defined by a specific iterative process. It starts with a positive integer a0​ and computes subsequent terms based on whether the current term is even or odd. The Juggler sequence follows a simple rule:

  • If the number is even, divide it by 2 (rounding down for any decimals).
  • If the number is odd, multiply it by 3 and add 1, then divide by 2 (again, rounding down).

This process continues until the sequence reaches 1. Here’s an example with a starting number of 9:

9 -> 27/2 (rounded down) -> 13
13 * 3 + 1 = 40
40/2 (rounded down) -> 20
20/2 (rounded down) -> 10
10/2 (rounded down) -> 5
5 * 3 + 1 = 16
16/2 (rounded down) -> 8
8/2 (rounded down) -> 4
4/2 (rounded down) -> 2
2/2 (rounded down) -> 1

This article explores two approaches for generating the Juggler Sequence in Java:

  • Iterative Approach (Loop): This method uses a loop to repeatedly calculate the next term based on the current value.
  • Recursive Approach: This approach utilizes a recursive function that calls itself with the next term until the sequence reaches 1.

2. Implementing the Juggler Sequence in Java

2.1 Iterative Approach

Here’s the Java code to generate the juggler sequence using the iterative approach:

import java.util.ArrayList;
import java.util.List;

public class JugglerSequence {

    // Method to generate the juggler sequence
    public static List<Integer> generateSequence(int a0) {
        if (a0 <= 0) {
      throw new IllegalArgumentException("Input number must be positive");
    }
        List<Integer> sequence = new ArrayList<>();
        int current = a0;

        // Add the initial term to the sequence
        sequence.add(current);

        // Generate subsequent terms until reaching 1
        while (current != 1) {
            int next;
            if (current % 2 == 0) {
                // If current term is even
                next = (int) Math.sqrt(current);
            } else {
                // If current term is odd
                next = (int) Math.sqrt(current * current * current);
            }
            sequence.add(next);
            current = next;
        }
        return sequence;
    }

    // Method to print the sequence
    public static void printSequence(List<Integer> sequence) {
        System.out.println("Juggler Sequence:");
        for (int num : sequence) {
            System.out.print(num + " ");
        }
        System.out.println();
    }

    // Main method to test the sequence generation
    public static void main(String[] args) {
        int startingNumber = 3;  // Change this to your desired starting number
        List<Integer> jugglerSequence = generateSequence(startingNumber);
        printSequence(jugglerSequence);
    }
}
  • generateSequence(int a0): This method takes the initial term a0​ as input and computes the entire Juggler sequence based on the described iterative process. It uses a List<Integer> to store the sequence.
  • printSequence(List<Integer> sequence): This method simply prints the generated sequence to the console.
  • main(String[] args): In the main method, we can specify the starting number (startingNumber) and then generate and print the corresponding Juggler sequence using the generateSequence and printSequence methods.

Example Output

If we run the above program with a0 = 3, the output will be:

Fig 1. Output displaying the Juggler sequence starting from 3
Fig 1. Output displaying the Juggler sequence starting from 3

2.2 Recursive Approach

This approach uses recursion to define the logic for generating the next term:

public class RecursiveJugglerSequence {

    // Method to generate the juggler sequence recursively
    public static List<Integer> generateSequence(int a0) {
        List<Integer> sequence = new ArrayList<>();
        generateSequenceRecursive(a0, sequence);
        return sequence;
    }

    // Helper method for recursive sequence generation
    private static void generateSequenceRecursive(int current, List<Integer> sequence) {
        sequence.add(current); // Add current term to the sequence
        
        if (current == 1) {
            return; // Base case: Sequence terminates when current term is 1
        }

        int next;
        if (current % 2 == 0) {
            next = (int) Math.sqrt(current); // Next term for even current
        } else {
            next = (int) Math.sqrt(current * current * current); // Next term for odd current
        }

        generateSequenceRecursive(next, sequence); // Recursive call with the next term
    }

    // Method to print the sequence
    public static void printSequence(List<Integer> sequence) {
        System.out.println("Juggler Sequence:");
        for (int num : sequence) {
            System.out.print(num + " ");
        }
        System.out.println();
    }

    // Main method to test the recursive sequence generation
    public static void main(String[] args) {
        int startingNumber = 9; // Change this to your desired starting number
        List<Integer> jugglerSequence = generateSequence(startingNumber);
        printSequence(jugglerSequence);
    }
}

In this example:

generateSequenceRecursive(int current, List<Integer> sequence) is the recursive helper method responsible for generating the sequence. It takes the current term (current) and the sequence list as parameters. It adds the current term to the sequence and checks if the sequence should terminate (when current becomes 1). If not, it calculates the next term (next) based on whether the current term is even or odd and recursively calls itself with next to continue the sequence generation.

Example Output

For example, if we run the above program with the starting number as 9, the output will be:

Juggler Sequence:
9 27 140 11 36 6 2 1 

3. Conclusion

In this article, we explored how to generate the Juggler sequence using Java programming, focusing on both iterative and recursive implementations. The program demonstrates the use of loops, conditional statements, method recursion and mathematical computations to generate and the sequence efficiently. You can modify the main method to try different initial values and observe the resulting Juggler sequences.

4. Download the Source Code

This was an article on how to generate a juggler sequence using Java.

Download
You can download the full source code of this example here: Generate a juggler sequence using Java

Omozegie Aziegbe

Omos Aziegbe is a technical writer and web/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button