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

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

Google Analytics Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.

HotJar Cookies

We use Hotjar in order to better understand our users’ needs and to optimize this service and experience. Hotjar is a technology service that helps us better understand our users’ experience (e.g. how much time they spend on which pages, which links they choose to click, what users do and don’t like, etc.) and this enables us to build and maintain our service with user feedback. Hotjar uses cookies and other technologies to collect data on our users’ behavior and their devices. This includes a device's IP address (processed during your session and stored in a de-identified form), device screen size, device type (unique device identifiers), browser information, geographic location (country only), and the preferred language used to display our website. Hotjar stores this information on our behalf in a pseudonymized user profile. Hotjar is contractually forbidden to sell any of the data collected on our behalf.

For further details, please see the ‘about Hotjar’ section of Hotjar’s support site.