![]() |
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 Table of ContentBrute forceIn 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) { Example: This example shows the use of the above-explained apporach. Javascript
Output
[ 1, 2, 7, 14 ] Optimization Using Square RootA 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) { Example: This example shows the use of the above-explained approach. Javascript
Output
[ 1, 12, 2, 6, 3, 4 ] |
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |