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 ]

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

Table of Content

  • Brute force
  • Optimization Using Square Root

Similar Reads

Brute force

...

Optimization Using Square Root

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....