Open In App

JavaScript Program to find All Divisors of a Natural Number

Last Updated : 03 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 ]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads