Horje
JavaScript Program to find All Divisors of a Natural Number

In this article, we are going to implement a program through which we can find the divisors of any natural number. Divisors refer to the numbers by which we can divide another number, resulting in zero remainder. These divisors are also commonly referred to as factors.

Example:

Input: 14
Output: 1,2,7,14

Brute force

In this approach, we iterate through all positive integers from 1 to the given number and check if each integer is a divisor. We collect all the divisors you find during this process.

Syntax:

if (n % i === 0) {
divisors.push(i);
}

Example: This example shows the use of the above-explained apporach.

Javascript

const findDivisors = () => {
    const divisors = [];
    for (let i = 1; i <= n; i++) {
        if (n % i === 0) {
            divisors.push(i);
        }
    }
    return divisors;
};
  
let n = 14;
console.log(findDivisors(n));

Output

[ 1, 2, 7, 14 ]

Optimization Using Square Root

A more efficient approach is to iterate only up to the square root of the given number. If a number ‘x’ is a divisor, then ‘n / x’ is also a divisor, where ‘n’ is the given number.

Syntax:

if (n % i === 0) {
divisors.push(i);
if (i !== n / i) {
divisors.push(n / i);
}
}

Example: This example shows the use of the above-explained approach.

Javascript

const findDivisors = () => {
    const divisors = [];
    for (let i = 1; i * i <= n; i++) {
        if (n % i === 0) {
            divisors.push(i);
            if (i !== n / i) {
                divisors.push(n / i);
            }
        }
    }
    return divisors;
};
  
let n = 12;
console.log(findDivisors(n));

Output

[ 1, 12, 2, 6, 3, 4 ]



Reffered: https://www.geeksforgeeks.org


Geeks Premier League

Related
Different Types of API Gateways? Different Types of API Gateways?
Complete Guide to Redis Lists Complete Guide to Redis Lists
Load Balancing in Google Cloud Platform Load Balancing in Google Cloud Platform
3 Methods To Fix Taskbar Overflow Not Working on Windows 11 3 Methods To Fix Taskbar Overflow Not Working on Windows 11
5 Methods To Fix Unsupported 16-bit Application Error on Windows 10 5 Methods To Fix Unsupported 16-bit Application Error on Windows 10

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12