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>class RocketElementorAnimation{constructor(){this.deviceMode=document.createElement("span"),this.deviceMode.id="elementor-device-mode-wpr",this.deviceMode.setAttribute("class","elementor-screen-only"),document.body.appendChild(this.deviceMode)}_detectAnimations(){let t=getComputedStyle(this.deviceMode,":after").content.replace(/"/g,"");this.animationSettingKeys=this._listAnimationSettingsKeys(t),document.querySelectorAll(".elementor-invisible[data-settings]").forEach(t=>{const e=t.getBoundingClientRect();if(e.bottom>=0&&e.top<=window.innerHeight)try{this._animateElement(t)}catch(t){}})}_animateElement(t){const e=JSON.parse(t.dataset.settings),i=e._animation_delay||e.animation_delay||0,n=e[this.animationSettingKeys.find(t=>e[t])];if("none"===n)return void t.classList.remove("elementor-invisible");t.classList.remove(n),this.currentAnimation&&t.classList.remove(this.currentAnimation),this.currentAnimation=n;let s=setTimeout(()=>{t.classList.remove("elementor-invisible"),t.classList.add("animated",n),this._removeAnimationSettings(t,e)},i);window.addEventListener("rocket-startLoading",function(){clearTimeout(s)})}_listAnimationSettingsKeys(t="mobile"){const e=[""];switch(t){case"mobile":e.unshift("_mobile");case"tablet":e.unshift("_tablet");case"desktop":e.unshift("_desktop")}const i=[];return["animation","_animation"].forEach(t=>{e.forEach(e=>{i.push(t+e)})}),i}_removeAnimationSettings(t,e){this._listAnimationSettingsKeys().forEach(t=>delete e[t]),t.dataset.settings=JSON.stringify(e)}static run(){const t=new RocketElementorAnimation;requestAnimationFrame(t._detectAnimations.bind(t))}}document.addEventListener("DOMContentLoaded",RocketElementorAnimation.run);</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>
	</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
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x