# Factors of a Number | JavaScript Program | Optimized Way

Factors of a number

**💡 What are the Factors of any number?**

Factors of any number (n) will be those numbers that exactly divide it and give a remainder as 0.

This means that the two whole numbers whose product is given number (n) are the factors of that number.

💡 **What are the Prime numbers?**

Prime numbers are natural numbers that are divisible by only 1 and the number itself.

In other words, prime numbers are positive integers greater than 1 with exactly two factors, 1 and the number itself.

The first ten primes are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29.

2 is the smallest prime number and is the only even prime number.

💡**What are Composite Numbers?**

In Mathematics, composite numbers are numbers that have more than two factors. These numbers are also called composites.

Composite numbers are just the opposite of prime numbers.

All the natural numbers which are not prime numbers are composite numbers as they can be divided by more than two numbers.

For example, 6 is a composite number because it is divisible by 1, 2, 3, and even by 6.

The smallest composite number is 4.

1 only has one factor which is 1, 2 has two factors that is 1 & 2, and 3 also has two factors that is 1 & 3.

4 have three factors that are 1, 2, and 4. So 4 is the smallest composite number.

**NOTE: Always remember that 1 is neither prime nor composite.**

💻

Program to find factors of a given number.

```
function printFactors(n) {
let factors = '';
for (let index = 1; index <= n; index++) {
if (n % index === 0) {
factors += index + ' ';
}
}
console.log(factors);
return factors;
}
```

```
printFactors(15) // 1 3 5 15
printFactors(150) // 1 2 3 5 6 10 15 25 30 50 75 150
printFactors(100) // 1 2 4 5 10 20 25 50 100
```

**Time Complexity of the above program – O(n)**.

💻

Optimized version of factor program – O(SQRT(n)).

```
Factor of 100 > 1 2 4 5 10 20 25 50 100
100 / 1 = 100
100 / 2 = 50
100 / 4 = 25
100 / 5 = 20
100 / 10 = 10
```

With the above factors, we can clearly see that if ** i** is a factor of a given number then

` `

**is also a factor of that number.**

`n/i`

So instead of running the loop till n, we can run that loop to SQRT(n) and read both **i** and **n / i **numbers.

function printFactorsOptimized(n) { let factors = ''; const sqrtOfN = Math.floor(Math.sqrt(n)); for (let index = 1; index <= sqrtOfN; index++) { if (n % index === 0) { factors += index + ' '; if (index !== n / index) { factors += n / index + ' '; } } } console.log(factors); return factors; }

**The second way to write the same above program without using the Math SQRT method – **

```
function printFactorsOptimized2(n) {
let factors = '';
for (let index = 1; index <= n; index++) {
if (index * index > n) {
break;
}
if (n % index === 0) {
factors += index + ' ';
if (index !== n / index) {
factors += n / index + ' ';
}
}
}
console.log('printFactorsOptimized2 -', factors);
return factors;
}
```

**So in the above code – If n is 100 & i is 11 then 11 * 11 = 121 which is > 100, which means there are no factors above i > 10. We will terminate our iteration when i * i > n.**

💻

Program to write Count number of factors

```
function countFactors(n) {
let count = 0;
const sqrtOfN = Math.floor(Math.sqrt(n));
for (let i = 1; i <= sqrtOfN; i++) {
if (n % i === 0) {
if (i === n / i) {
count++;
} else {
count += 2;
}
}
}
console.log(count)
return count;
}
```

```
countFactors(100) // 9
countFactors(97) // 2
countFactors(11) // 2
```

- CSS Display Property – Deep dive in block | inline | inline-block
- Implementation of Queue using Linked List | JavaScript
- Insert node in Linked list | Algorithm | JavaScript
- Insertion Sort in data structure | Algorithm with Examples
- Selection Sort Algorithm & K’th Largest Element in Array
- Quick Sort Algorithm with example | Step-by-Step Guide
- Dependency Inversion Principle with Example | Solid Principles
- Object-Oriented Programming | Solid Principles with Examples
- ASCII Code of Characters | String Operations with ASCII Code
- Negative Binary Numbers & 2’s Complement | Easy explanation
- Factors of a Number | JavaScript Program | Optimized Way
- LeetCode – Game of Life Problem | Solution with JavaScript
- Fibonacci series using Recursion | While loop | ES6 Generator
- JavaScript Coding Interview Question & Answers
- LeetCode – Coin Change Problem | Dynamic Programming | JavaScript
- HackerRank Dictionaries and Maps Problem | Solution with JavaScript
- React Redux Unit Testing of Actions, Reducers, Middleware & Store
- Micro frontends with Module Federation in React Application
- React Interview Question & Answers – Mastering React
- Top React Interview Question & Answer | React Routing
- React Interview Questions and Answers | React hooks
- Higher Order Component with Functional Component | React JS
- Top React Interview Questions and Answers | Must Know
- Interview Question React | Basics for Freshers and Seniors
- Cyber Security Fundamental Questions & Answers You must know
- Application & Web Security Interview Questions & Answers
- Top Scrum Master and Agile Question & Answers 2022
- Trapping Rain Water Leetcode Problem Solution
- Array Representation of Binary Tree | Full Tree & Complete Binary Tree
- Graphs in Data Structure, Types & Traversal with BFS and DFS, Algorithms
- Traversing 2 D array with BFS & DFS Algorithm in JavaScript
- Time Complexity & Calculations | All You should know
- Backspace String Compare Leetcode Problem & Solution
- Angular Interview Questions & Answers 2021 – Part 3 – JS Mount
- Why Angular is a Preferred Choice for Developers? Top Features
- Angular Interview Questions & Answers You should know Part 2
- Top 30 JavaScript Interview Questions and Answers for 2021
- React JS Stripe Payment Gateway Integration with Node | Step by Step Guide
- Create Year Month & Date dropdown List using JavaScript & JQuery
- Create Custom QR Code Component using QR Code Styling in React JS
- How to create a common Helper class or util file in React JS
- React Build Routing with Fixed Header and Navigation | React Router Tutorial
- React Create Dashboard Layout with Side Menu, Header & Content Area
- Web Application Security Best Practices | Top Tips to Secure Angular App
- HTML Form with Pure CSS & JavaScript | Custom Radio and Checkbox
- NgRx Top Interview Questions and Answers You should know
- Top 40 Awesome CSS Interview Questions & Answers You should know | CSS Tutorial
- Tips to Boost Angular App Performance | Web page Speed Optimization
- JavaScript Rotate 2D matrix 90 degrees clockwise | Top Interview Question
- HashTable Data Structure in JavaScript with Add Delete & Search Algorithms
- Trie Data Structure – Insert Search Delete & Print Program with JavaScript
- Top JavaScript Commonly asked Algorithms in Interview
- JavaScript String Permutation Program with nice explanation
- Angular NgModule, AOT, and DI, and EntryComponents with example
- Angular Dependency Injection Provider and Types of Provider
- TypeScript New & Latest Features You should know | JS Mount
- Rx JS Top Operators with examples | Rx JS interview questions
- What’s new in Angular 9 | Top updates in Angular 9 By JS mount
- What’s new in Angular 8 | Angular 8 Latest Feature By JS mount
- Prime NG Row Group with Subheader and Totals Row
- How to implement Reactive Form with Prime NG table
- Angular Unit Testing Spy, Router, Fake Async, tick, & Subscribe
- Angular Auto Tab Directive : Auto focus on next field
- VS Code Useful Extensions for Web Development
- Angular HTTP Request Testing with HttpClientTestingModule & HttpTestingController
- Dynamic Tooltip with Angular Pipe: Performance Orientation
- Konva JS Event Handling and Get Overlapped Shapes where clicked
- JavaScript Top Interview questions & Answers You should know
- Best Practices for Writing Angular Apps | Angular Guidelines
- Top 30 TypeScript Interview Questions & Answers You Must Know
- HR Interview Questions and Answers for Experienced
- Mastering JavaScript Interview Questions & Answers
- Commonly Asked Coding Interview Questions JavaScript
- Angular Interview Question & Answers for Experienced – Part 1
- Most Asked JavaScript Interview Questions for Experienced
- Frequently Asked HTML Interview Questions and Answers
- How to upload Image in Node JS & Handle file size, file type error with Multer
- Angular Custom directive to match password and confirm password
- Draw Canvas Image, Line & Circle With HTML & JavaScript
- HTML Interview Questions and Answers on Canvas