How to find the divisors of a number in JavaScript

2 Answers

0 votes
function printDivisors(n) {
    for (let i = 1; i <= n; i++) {
        if (n % i === 0) {
            console.log(i);
        }
    } 
}
 
let n = 24;
    
printDivisors(n);



/*
run:

1
2
3
4
6
8
12
24

*/

 



answered Jul 1, 2020 by avibootz
0 votes
function printDivisors(n) {
     for (let i = 1; i <= Math.sqrt(n); i++) { 
        if (n % i === 0) { 
            if (n / i === i) 
                console.log(i + ", "); 
            else
                console.log(i + ", " + n/ i + ", "); 
        } 
    } 
}


let n = 24;
    
printDivisors(n);



/*
run:

1, 24, 
2, 12, 
3, 8, 
4, 6, 

*/

 



answered Jul 1, 2020 by avibootz

Related questions

1 answer 124 views
1 answer 101 views
2 answers 178 views
2 answers 262 views
2 answers 164 views
164 views asked Jul 1, 2020 by avibootz
2 answers 197 views
2 answers 174 views
174 views asked Jun 30, 2020 by avibootz
...