1
+ /*
2
+ JS solution for challenge: "Divisors of a Number"
3
+ To test the solution, type from CLI: node solution.js
4
+ */
5
+
6
+ function divisors ( number ) {
7
+ // Variables declarations
8
+ let divisor = 1 ;
9
+ let count = 0 ;
10
+ let quotient = number ;
11
+ while ( divisor <= quotient ) {
12
+ // The number is divisible by the divisor
13
+ if ( number % divisor == 0 ) {
14
+ // If the quotient is greater than the divisor both must be counted otherwise only the divisor
15
+ quotient > divisor ? count += 2 : count += 1
16
+ }
17
+ // New divisor and new quotient to consider for the next iteration
18
+ divisor += 1 ;
19
+ quotient = number / divisor ;
20
+ }
21
+ return count
22
+ }
23
+
24
+
25
+ // TEST CASES
26
+ console . log ( "\nExpected sequence: 1 2 2 3 2 2 6 8 8 6 8 10 4 2:" )
27
+ sequence = ""
28
+ console . log ( " divisors(1) = " + divisors ( 1 ) + " | | | | | | | | | | || | |" ) // expected 1 (1)
29
+ sequence += divisors ( 1 )
30
+ console . log ( " divisors(2) = " + divisors ( 2 ) + " | | | | | | | | | || | |" ) // expected 2 (1,2)
31
+ sequence += divisors ( 2 )
32
+ console . log ( " divisors(3) = " + divisors ( 3 ) + " | | | | | | | | || | |" ) // expected 2 (1,3)
33
+ sequence += divisors ( 3 )
34
+ console . log ( " divisors(4) = " + divisors ( 4 ) + " | | | | | | | || | |" ) // expected 3 (1,2,4)
35
+ sequence += divisors ( 4 )
36
+ console . log ( " divisors(5) = " + divisors ( 5 ) + " | | | | | | || | |" ) // expected 2 (1,5)
37
+ sequence += divisors ( 5 )
38
+ console . log ( " divisors(7) = " + divisors ( 7 ) + " | | | | | || | |" ) // expected 2 (1,7)
39
+ sequence += divisors ( 7 )
40
+ console . log ( " divisors(12) = " + divisors ( 12 ) + " | | | | || | |" ) // expected 6 (1,2,3,4,6,12)
41
+ sequence += divisors ( 12 )
42
+ console . log ( " divisors(24) = " + divisors ( 24 ) + " | | | || | |" ) // expected 8 (1,2,3,4,6,8,12,24)
43
+ sequence += divisors ( 24 )
44
+ console . log ( " divisors(30) = " + divisors ( 30 ) + " | | || | |" ) // expected 8 (1,2,3,5,6,10,15,30)
45
+ sequence += divisors ( 30 )
46
+ console . log ( " divisors(99) = " + divisors ( 99 ) + " | || | |" ) // expected 6 (1,3,9,11,33,99)
47
+ sequence += divisors ( 99 )
48
+ console . log ( " divisors(130) = " + divisors ( 130 ) + " || | |" ) // expected 8 (1,2,5,10,13,26,65,130)
49
+ sequence += divisors ( 130 )
50
+ console . log ( " divisors(1875) = " + divisors ( 1875 ) + " | |" ) // expected 10 (1,3,5,15,25,75,125,375,625,1875)
51
+ sequence += divisors ( 1875 )
52
+ console . log ( " divisors(4997) = " + divisors ( 4997 ) + " |" ) // expected 4 (1,19,263,4997)
53
+ sequence += divisors ( 4997 )
54
+ console . log ( " divisors(10589) = " + divisors ( 10589 ) ) // expected 2 (1,10589)
55
+ sequence += divisors ( 10589 )
56
+ sequence === '122322688681042' ? console . log ( '\nCongratulations, all tests have been passed.' ) : console . log ( '\nAttention, tests failed.' )
0 commit comments