
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Make Ulam Number Sequence in JavaScript
A mathematician Ulam proposed generating a sequence of numbers from any positive integer n (n>0) as follows −
If n is 1, it will stop. if n is even, the next number is n/2. if n is odd, the next number is 3 * n + 1. continue with the process until reaching 1.
Here are some examples for the first few integers −
2->1 3->10->5->16->8->4->2->1 4->2->1 6->3->10->5->16->8->4->2->1 7->22->11->34->17->52->26->13->40->20->10->5->16->8->4->2->1
We are required to write a JavaScript function that takes in a number and returns the Ulam sequence starting with that number.
Example
The code for this will be −
const num = 7; const generateUlam = num => { const res = [num]; if(num && num === Math.abs(num) && isFinite(num)){ while (num !== 1) { if(num % 2){ num = 3 * num + 1 }else{ num /= 2; }; res.push(num); }; }else{ return false; }; return res; }; console.log(generateUlam(num)); console.log(generateUlam(3));
Output
And the output in the console will be −
[ 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1 ] [ 3, 10, 5, 16, 8, 4, 2, 1 ]
Advertisements