1+ // Path: src/02-bigOnotation/01-big-o-intro.js
2+
3+ // O(1) - Constant Time
4+ function multiplyBy3 ( num ) {
5+ console . log ( `${ num } * 3 = ` , num * 3 ) ;
6+ }
7+
8+ console . log ( 'O(1) - Constant Time' ) ;
9+ multiplyBy3 ( 5 ) ;
10+ multiplyBy3 ( 50 ) ;
11+
12+ // O(n) - Linear Time
13+ function multiplicationTable ( num , x ) {
14+ for ( let i = 1 ; i <= x ; i ++ ) {
15+ console . log ( `${ num } * ${ i } = ` , num * i ) ;
16+ }
17+ }
18+
19+ console . log ( '*******************' ) ;
20+ console . log ( 'O(n) - Linear Time' ) ;
21+ console . log ( 'Multiplication table for 5 with x = 3' ) ;
22+ multiplicationTable ( 5 , 3 ) ;
23+
24+ console . log ( 'Multiplication table for 5 with x = 10' ) ;
25+ multiplicationTable ( 5 , 10 ) ;
26+
27+ // O(n^2) - Quadratic Time
28+ function multiplicationTable2 ( num , x ) {
29+ for ( let i = 1 ; i <= num ; i ++ ) {
30+ console . log ( `Multiplication table for ${ i } with x = ${ x } ` ) ;
31+ for ( let j = 1 ; j <= x ; j ++ ) {
32+ console . log ( `${ i } * ${ j } = ` , i * j ) ;
33+ }
34+ }
35+ }
36+
37+ console . log ( '************************' ) ;
38+ console . log ( 'O(n^2) - Quadratic Time' ) ;
39+ multiplicationTable2 ( 3 , 2 ) ;
40+
41+ // O(nˆ3) - Cubic Time
42+ function multiplicationTable3 ( num , x ) {
43+ for ( let i = 1 ; i <= num ; i ++ ) {
44+ for ( let j = 1 ; j <= x ; j ++ ) {
45+ for ( let k = 1 ; k <= x ; k ++ ) {
46+ console . log ( `${ i } * ${ j } * ${ k } = ` , i * j * k ) ;
47+ }
48+ }
49+ }
50+ }
51+
52+ console . log ( '************************' ) ;
53+ console . log ( 'O(n^3) - Cubic Time' ) ;
54+ multiplicationTable3 ( 2 , 3 ) ;
55+
56+ // calculating the time complexity of the function
57+ function multiplicationTableRefactored ( num , x ) {
58+
59+ let s = '' ; // {1}
60+ let numberOfAsterisks = num * x ; // {2}
61+ for ( let i = 1 ; i <= numberOfAsterisks ; i ++ ) { // {3}
62+ s += '*' ;
63+ }
64+ console . log ( s ) ; // {4}
65+ console . log ( 'Calculating the time complexity of a function' ) ; // {5}
66+
67+ for ( let i = 1 ; i <= num ; i ++ ) { // {6}
68+ console . log ( `Multiplication table for ${ i } with x = ${ x } ` ) ; // {7}
69+ for ( let j = 1 ; j <= x ; j ++ ) { // {8}
70+ console . log ( `${ i } * ${ j } = ` , i * j ) ; // {9}
71+ }
72+ }
73+ }
74+
75+ multiplicationTableRefactored ( 3 , 2 ) ;
76+ // to see the output of this file use the command: node src/02-bigOnotation/01-big-o-intro.js
0 commit comments