
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Factorize a number in JavaScript
We are required to write a JavaScript function that takes in a positive integer as the only argument. The function should construct and return an array of all the numbers that exactly divide the input number.
For example −
If the input number is −
const num = 12;
Then the output should be −
const output = [1, 2, 3, 4, 6, 12];
Example
Following is the code −
const findFactors = (num = 1) => { let half = Math.floor(num / 2); const res = [1]; // 1 will be a part of every solution. let i, j; num % 2 === 0 ? (i = 2, j = 1) : (i = 3, j = 2); for (i; i <= half; i += j) { if(num % i === 0){ res.push(i); }; }; res.push(num); return res; }; console.log(findFactors(12));
Output
Following is the output on console −
[ 1, 2, 3, 4, 6, 12 ]
- Related Articles
- Reverse a number in JavaScript
- Weekday as a number in JavaScript?
- Validate a number as Fibonacci series number in JavaScript
- Is the reversed number a prime number in JavaScript
- Finding whether a number is triangular number in JavaScript
- Returning number of digits in factorial of a number in JavaScript
- Greatest digit of a number in JavaScript
- Finding closed loops in a number - JavaScript
- Squared concatenation of a Number in JavaScript
- Decimal count of a Number in JavaScript
- Separating digits of a number in JavaScript
- Armstrong number within a range in JavaScript
- Checking for a Doubleton Number in JavaScript
- Digit sum upto a number of digits of a number in JavaScript
- Finding a number, when multiplied with input number yields input number in JavaScript

Advertisements