Collatz (3n + 1) sequence in JavaScript

problem

You wish to generate the Collatz sequence using JavaScript. In this post we will see how to accomplish that and print in the console of the web browser that is in the web developer tools of each popular web browser. Recall the Collatz sequence starts by giving an input a natural number greater than 0 and it always ends with the number 1. If the number given is odd then the it’s multiplied by 3 and adding 1 to it. If it’s even we divide it by 2.

Following the logic, we can see a simple example below:

Input of even number: 6
6
3
10
5
16
8
4
2
1
Input of odd number: 5
5
16
8
4
2
1

SOLUTION

Let’s write a function that simply returns the next number in the sequence. For example:

				
					<script>

function collatz(n) 
{
	if (n % 2 == 0)
	{
		return n / 2;
	}else 
	{
		return 3 * n + 1;
	
	}
}

</script>
				
			

I created a script tag and added the collatz(n) function that generates the next Collatz number. If you save it to an HTML file and open it in the web browser, we can call this function using the console.

When clicking the button, you will see a blank page because it only contain the JavaScript function above.

running

If you’re using Firefox, the web developer tools can be brought up by Right clicking on the screen and then click Inspect. From the popup window, under Console tab, call the function with a parameter as shown below:

output in javascript console

It works!

If you wish to show the result on the web page then we need to add some additional tags and then manipulate them via JavaScript.

One idea would be to have the input given via a text box and next to it a button that when it’s clicked it will show the results below.

Let’s create the text box and button and the result placeholder in the HTML. For example:

				
					<!DOCTYPE html>
	<body>
		<h3>Collatz sequence</h3>
		<hr/>

		<input type="text" id="txtNumber" placeholder="Enter a number"/>
		<input type="button" onclick="generateCollatz()" value="Generate" />
		<div id="result">
			
		</div>
	<script>var rocket_beacon_data = {"ajax_url":"https:\/\/programmerabroad.com\/wp-admin\/admin-ajax.php","nonce":"961ed9db5a","url":"https:\/\/programmerabroad.com\/collatz-3n-1-sequence-in-javascript","is_mobile":false,"width_threshold":1600,"height_threshold":700,"delay":500,"debug":null,"status":{"lrc":true},"lrc_threshold":1800}</script><script data-name="wpr-wpr-beacon" src='https://programmerabroad.com/wp-content/plugins/wp-rocket/assets/js/wpr-beacon.min.js' async></script></body>
</html>
				
			

When the button is clicked, the generateCollatz function is called. Let’s create this function. It will take the input number from the text box and call collatz function iteratively and print out the results on the div with id “result”.

 

The function is as follows:

				
					function generateCollatz() 
{
	//get the input
	let num = document.getElementById("txtNumber").value;
	//calculate next number in sequence
	var next = collatz(num);
	//this is gonna be the output as string
	var result = "Collatz: " + next;

	//iterate until is 1
	while (next != 1) {
		
		//calculate next
		next = collatz(next);

		//update the result by appending the number
		result += ", " + next;
	}

	//set the result string on the div
	document.getElementById("result").innerHTML = result;
}
				
			

Comments are added for extra clarity.

Adding the two functions together in the script tag and merging it with the HTML code above will look like as follows:

				
					<!DOCTYPE html>
	<body>
		<h3>Collatz sequence</h3>
		<hr/>

		<input type="text" id="txtNumber" placeholder="Enter a number"/>
		<input type="button" onclick="generateCollatz()" value="Generate" />
		<div id="result">
			
		</div>
	<script>var rocket_beacon_data = {"ajax_url":"https:\/\/programmerabroad.com\/wp-admin\/admin-ajax.php","nonce":"961ed9db5a","url":"https:\/\/programmerabroad.com\/collatz-3n-1-sequence-in-javascript","is_mobile":false,"width_threshold":1600,"height_threshold":700,"delay":500,"debug":null,"status":{"lrc":true},"lrc_threshold":1800}</script><script data-name="wpr-wpr-beacon" src='https://programmerabroad.com/wp-content/plugins/wp-rocket/assets/js/wpr-beacon.min.js' async></script></body>

	<script>
		function generateCollatz() 
		{
			//get the input
			let num = document.getElementById("txtNumber").value;
			//calculate next number in sequence
			var next = collatz(num);
			//this is gonna be the output as string
			var result = "Collatz: " + next;

			//iterate until is 1
			while (next != 1) {
				
				//calculate next
				next = collatz(next);

				//update the result by appending the number
				result += ", " + next;
			}

			//set the result string on the div
			document.getElementById("result").innerHTML = result;
		}

		function collatz(n) 
		{
			if (n % 2 == 0)
			{
				return n / 2;
			}else 
			{
				return 3 * n + 1;
			
			}
		}

	</script>
</html>
				
			
output

You can see multiple inputs below:

The complete HTML file is available by the link below. You can check it out in your browser by clicking on it or download it:

conclusion

In this post we saw how to generate the Collatz sequence using vanilla JavaScript and how to print the result in the JavaScript console but also on the web page. The code can of course be improved to handle some data input validation as the functions are designed to work with natural numbers greater than 0. It’s interesting how this sequence always ends up with 1!

Share it!

Facebook
Twitter
LinkedIn
Reddit
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x