JavaScript Data Structures and Algorithms An Introduction to Understanding and Implementing Core Data Structure and Algorithm Fundamentals 1st Editon by Sammie Bae ISBN 1484239873 9781484239872 - The complete ebook is available for download with one click
JavaScript Data Structures and Algorithms An Introduction to Understanding and Implementing Core Data Structure and Algorithm Fundamentals 1st Editon by Sammie Bae ISBN 1484239873 9781484239872 - The complete ebook is available for download with one click
https://ebookball.com/product/a-practical-introduction-to-data-
structures-and-algorithm-analysis-3rd-edition-by-clifford-
shaffer-15310/
https://ebookball.com/product/data-structures-and-algorithms-1st-
edition-by-alfred-aho-isbn-0201000237-9780201000238-25072/
https://ebookball.com/product/data-structures-and-algorithm-analysis-
in-javatm-3rd-edition-by-mark-weiss-9780133465013-0133465012-18710/
Data Structures And Algorithm Analysis in C 4th Edition by
Mark Weiss 013284737X 9780132847377
https://ebookball.com/product/data-structures-and-algorithm-analysis-
in-c-4th-edition-by-mark-weiss-013284737x-9780132847377-15292/
https://ebookball.com/product/data-structures-and-algorithms-in-
java-1st-edition-by-peter-drake-isbn-0131469142-9780131469143-12422/
https://ebookball.com/product/data-structures-and-algorithms-in-c-1st-
edition-by-adam-drozdek-asin-b002wlxmby-25076/
https://ebookball.com/product/data-structures-and-algorithm-analysis-
in-c-3rd-edition-by-clifford-shaffer-
isbn-048648582x-978-0486485829-16486/
https://ebookball.com/product/data-structures-algorithms-and-
applications-in-c-1st-edition-by-adam-drozdek-
isbn-1133608426-9781133608424-17250/
JavaScript Data
Structures and
Algorithms
An Introduction to Understanding and
Implementing Core Data Structure and
Algorithm Fundamentals
—
Sammie Bae
JavaScript Data Structures
and Algorithms
An Introduction to Understanding
and Implementing Core Data
Structure and Algorithm
Fundamentals
Sammie Bae
JavaScript Data Structures and Algorithms
Sammie Bae
Hamilton, ON, Canada
Acknowledgments ��������������������������������������������������������������������������������������������������xix
Introduction ������������������������������������������������������������������������������������������������������������xxi
v
Table of Contents
vi
Table of Contents
String Shortening������������������������������������������������������������������������������������������������������������������������ 43
Encryption����������������������������������������������������������������������������������������������������������������������������������� 45
RSA Encryption���������������������������������������������������������������������������������������������������������������������� 46
Summary������������������������������������������������������������������������������������������������������������������������������� 50
vii
Table of Contents
Chapter 8: Recursion���������������������������������������������������������������������������������������������� 99
Introducing Recursion����������������������������������������������������������������������������������������������������������������� 99
Rules of Recursion�������������������������������������������������������������������������������������������������������������������� 100
Base Case���������������������������������������������������������������������������������������������������������������������������� 100
Divide-and-Conquer Method����������������������������������������������������������������������������������������������� 101
Classic Example: Fibonacci Sequence�������������������������������������������������������������������������������� 101
Fibonacci Sequence: Tail Recursion������������������������������������������������������������������������������������ 102
Pascal’s Triangle������������������������������������������������������������������������������������������������������������������ 103
Big-O for Recursion������������������������������������������������������������������������������������������������������������������� 105
Recurrence Relations���������������������������������������������������������������������������������������������������������� 105
Master Theorem������������������������������������������������������������������������������������������������������������������ 106
Recursive Call Stack Memory��������������������������������������������������������������������������������������������������� 107
Summary���������������������������������������������������������������������������������������������������������������������������������� 109
Exercises����������������������������������������������������������������������������������������������������������������������������������� 109
viii
Table of Contents
ix
Table of Contents
x
Table of Contents
xi
Table of Contents
xii
Table of Contents
xiii
Table of Contents
Index��������������������������������������������������������������������������������������������������������������������� 351
xiv
About the Author
Sammie Bae is a data engineer at Yelp and previously
worked for the data platform engineering team at
NVIDIA. He developed a deep interest in JavaScript
during an internship at SMART Technologies (acquired by
Foxconn), where he developed Node.js-based JavaScript
APIs for serial port communication between electronic
board drivers and a web application. Despite how relevant
JavaScript is to the modern software engineering industry,
currently no books besides this one teach algorithms and
data structures using JavaScript. Sammie understands how
difficult these computer science concepts are and aims to
provide clear and concise explanations in this book.
xv
About the Technical Reviewer
Phil Nash is a developer evangelist for Twilio, serving
developer communities in London and all over the world.
He is a Ruby, JavaScript, and Swift developer; Google
Developers Expert; blogger; speaker; and occasional brewer.
He can be found hanging out at meetups and conferences,
playing with new technologies and APIs, or writing open
source code.
xvii
Acknowledgments
Thank you, Phil Nash, for the valuable feedback that helped me improve the technical
content of this book with clear explanations and concise code.
Special thanks to the Apress team. This includes James Markham, Nancy Chen, Jade
Scard, and Chris Nelson. Finally, I want to thank Steve Anglin for reaching out to me to
publish with Apress.
xix
Introduction
The motivation for writing this book was the lack of resources available about data
structures and algorithms written in JavaScript. This was strange to me because
today many of the job opportunities for software development require knowledge of
JavaScript; it is the only language that can be used to write the entire stack, including the
front-end, mobile (native and hybrid) platforms, and back-end. It is crucial for JavaScript
developers to understand how data structures work and how to design algorithms to
build applications.
Therefore, this book aims to teach data structure and algorithm concepts from
computer science for JavaScript rather than for the more typical Java or C++. Because
JavaScript follows the prototypal inheritance pattern, unlike Java and C++ (which follow
the inheritance pattern), there are some changes in writing data structures in JavaScript.
The classical inheritance pattern allows inheritance by creating a blueprint-like form
that objects follow during inheritance. However, the prototypal inheritance pattern
means copying the objects and changing their properties.
This book first covers fundamental mathematics for Big-O analysis and then lays out
the basic JavaScript foundations, such as primitive objects and types. Then, this book
covers implementations and algorithms for fundamental data structures such as linked
lists, stacks, trees, heaps, and graphs. Finally, more advanced topics such as efficient
string search algorithms, caching algorithms, and dynamic programming problems are
explored in great detail.
xxi
CHAPTER 1
Big-O Notation
O(1) is holy.
—Hamid Tizhoosh
Before learning how to implement algorithms, you should understand how to analyze
the effectiveness of them. This chapter will focus on the concept of Big-O notation for
time and algorithmic space complexity analysis. By the end of this chapter, you will
understand how to analyze an implementation of an algorithm with respect to both time
(execution time) and space (memory consumed).
1
© Sammie Bae 2019
S. Bae, JavaScript Data Structures and Algorithms, https://doi.org/10.1007/978-1-4842-3988-9_1
Chapter 1 Big-O Notation
The following sections illustrate these common time complexities with some simple
examples.
Common Examples
O(1) does not change with respect to input space. Hence, O(1) is referred to as being
constant time. An example of an O(1) algorithm is accessing an item in the array by its
index. O(n) is linear time and applies to algorithms that must do n operations in the
worst-case scenario.
An example of an O(n) algorithm is printing numbers from 0 to n-1, as shown here:
1 function exampleLinear(n) {
2 for (var i = 0 ; i < n; i++ ) {
2
Chapter 1 Big-O Notation
3 console.log(i);
4 }
5 }
Similarly, O(n2) is quadratic time, and O(n3) is cubic time. Examples of these
complexities are shown here:
1 function exampleQuadratic(n) {
2 for (var i = 0 ; i < n; i++ ) {
3 console.log(i);
4 for (var j = i; j < n; j++ ) {
5 console.log(j);
6 }
7 }
8 }
1 function exampleCubic(n) {
2 for (var i = 0 ; i < n; i++ ) {
3 console.log(i);
4 for (var j = i; j < n; j++ ) {
5 console.log(j);
6 for (var k = j;
j < n; j++ ) {
7 console.log(k);
8 }
9 }
10 }
11 }
2,4,8,16,32,64
3
Chapter 1 Big-O Notation
The efficiency of logarithmic time complexities is apparent with large inputs such
as a million items. Although n is a million, exampleLogarithmic will print only 19
items because log2(1,000,000) = 19.9315686. The code that implements this logarithmic
behavior is as follows:
1 function exampleLogarithmic(n) {
2 for (var i = 2 ; i <= n; i= i*2 ) {
3 console.log(i);
4 }
5 }
4
Chapter 1 Big-O Notation
• Log of a power rule: log(nk) is O(log(n)) for any constant k > 0. With
the log of a power rule, constants within a log function are also
ignored in Big-O notation.
Special attention should be paid to the first three rules and the polynomial rule
because they are the most commonly used. I’ll discuss each of those rules in the
following sections.
This means that both 5f(n) and f(n) have the same Big-O notation of O(f(n)).
Here is an example of a code block with a time complexity of O(n):
1 function a(n){
2 var count =0;
3 for (var i=0;i<n;i++){
4 count+=1;
5 }
6 return count;
7 }
This block of code has f(n) = n. This is because it adds to count n times. Therefore,
this function is O(n) in time complexity:
1 function a(n){
2 var count =0;
3 for (var i=0;i<5*n;i++){
5
Chapter 1 Big-O Notation
4 count+=1;
5 }
6 return count;
7 }
This block has f(n) = 5n. This is because it runs from 0 to 5n. However, the first two
examples both have a Big-O notation of O(n). Simply put, this is because if n is close to
infinity or another large number, those four additional operations are meaningless. It is
going to perform it n times. Any constants are negligible in Big-O notation.
The following code block demonstrates another function with a linear time
complexity but with an additional operation on line 6:
1 function a(n){
2 var count =0;
3 for (var i=0;i<n;i++){
4 count+=1;
5 }
6 count+=3;
7 return count;
8 }
Lastly, this block of code has f(n) = n+1. There is +1 from the last operation
(count+=3). This still has a Big-O notation of O(n). This is because that 1 operation is not
dependent on the input n. As n approaches infinity, it will become negligible.
It is important to remember to apply the coefficient rule after applying this rule.
6
Chapter 1 Big-O Notation
The following code block demonstrates a function with two main loops whose time
complexities must be considered independently and then summed:
1 function a(n){
2 var count =0;
3 for (var i=0;i<n;i++){
4 count+=1;
5 }
6 for (var i=0;i<5*n;i++){
7 count+=1;
8 }
9 return count;
10 }
In this example, line 4 has f(n) = n, and line 7 has f(n) = 5n. This results in 6n.
However, when applying the coefficient rule, the final result is O(n) = n.
The following code block demonstrates a function with two nested for loops for
which the product rule is applied:
1 function (n){
2 var count =0;
3 for (var i=0;i<n;i++){
4 count+=1;
5 for (var i=0;i<5*n;i++){
6 count+=1;
7 }
8 }
9 return count;
10 }
7
Chapter 1 Big-O Notation
In this example, f(n) = 5n*n because line 7 runs 5n times for a total of n iterations.
Therefore, this results in a total of 5n2 operations. Applying the coefficient rule, the result
is that O(n)=n2.
1 function a(n){
2 var count =0;
3 for (var i=0;i<n*n;i++){
4 count+=1;
5 }
6 return count;
7 }
Summary
Big-O is important for analyzing and comparing the efficiencies of algorithms.
The analysis of Big-O starts by looking at the code and applying the rules to simplify
the Big-O notation. The following are the most often used rules:
8
Chapter 1 Big-O Notation
Exercises
Calculate the time complexities for each of the exercise code snippets.
EXERCISE 1
1 function someFunction(n) {
2
3 for (var i=0;i<n*1000;i++) {
4 for (var j=0;j<n*20;j++) {
5 console.log(i+j);
6 }
7 }
8
9 }
EXERCISE 2
1 function someFunction(n) {
2
3 for (var i=0;i<n;i++) {
4 for (var j=0;j<n;j++) {
5 for (var k=0;k<n;k++) {
6 for (var l=0;l<10;l++) {
7 console.log(i+j+k+l);
8 }
9 }
10 }
11 }
12
13 }
9
Chapter 1 Big-O Notation
EXERCISE 3
1 function someFunction(n) {
2
3 for (var i=0;i<1000;i++) {
4 console.log("hi");
5 }
6
7 }
EXERCISE 4
1 function someFunction(n) {
2
3 for (var i=0;i<n*10;i++) {
4 console.log(n);
5 }
6
7 }
EXERCISE 5
1 function someFunction(n) {
2
3 for (var i=0;i<n;i*2) {
4 console.log(n);
5 }
6
7 }
10
Chapter 1 Big-O Notation
EXERCISE 6
1 function someFunction(n) {
2
3 while (true){
4 console.log(n);
5 }
6 }
Answers
1. O(n2)
There are two nested loops. Ignore the constants in front of n.
2. O(n3)
There are four nested loops, but the last loop runs only until 10.
3. O(1)
Constant complexity. The function runs from 0 to 1000. This does
not depend on n.
4. O(n)
Linear complexity. The function runs from 0 to 10n. Constants are
ignored in Big-O.
5. O(log2n)
Logarithmic complexity. For a given n, this will operate only log2n
times because i is incremented by multiplying by 2 rather than
adding 1 as in the other examples.
6. O(∞)
11
CHAPTER 2
J avaScript Scope
The scope is what defines the access to JavaScript variables. In JavaScript, variables
can belong to the global scope or to the local scope. Global variables are variables that
belong in the global scope and are accessible from anywhere in the program.
1 test = "sss";
2 console.log(test); // prints "sss"
However, this creates a global variable, and this is one of the worst practices in
JavaScript. Avoid doing this at all costs. Always use var or let to declare variables.
Finally, when declaring variables that won’t be modified, use const.
Here’s an example:
1 function scope1(){
2 var top = "top";
3 bottom = "bottom";
4 console.log(bottom);
5
6 var bottom;
7 }
8 scope1(); // prints "bottom" - no error
How does this work? The previous is the same as writing the following:
1 function scope1(){
2 var top = "top";
3 var bottom;
4 bottom = "bottom"
5 console.log(bottom);
6 }
7 scope1(); // prints "bottom" - no error
The bottom variable declaration, which was at the last line in the function, is floated
to the top, and logging the variable works.
The key thing to note about the var keyword is that the scope of the variable is the
closest function scope. What does this mean?
In the following code, the scope2 function is the function scope closest to the print
variable:
1 function scope2(print){
2 if(print){
3 var insideIf = '12';
4 }
5 console.log(insideIf);
6 }
7 scope2(true); // prints '12' - no error
14
Chapter 2 JavaScript: Unique Parts
1 function scope2(print){
2 var insideIf;
3
4 if(print){
5 insideIf = '12';
6 }
7 console.log(insideIf);
8 }
9 scope2(true); // prints '12' - no error
In Java, this syntax would have thrown an error because the insideIf variable is
generally available only in that if statement block and not outside it.
Here’s another example:
1 var a = 1;
2 function four() {
3 if (true) {
4 var a = 4;
5 }
6
7 console.log(a); // prints '4'
8 }
4 was printed, not the global value of 1, because it was redeclared and available in
that scope.
1 function scope3(print){
2 if(print){
3 let insideIf = '12';
4 }
15
Chapter 2 JavaScript: Unique Parts
5 console.log(insideIf);
6 }
7 scope3(true); // prints ''
In this example, nothing is logged to the console because the insideIf variable is
available only inside the if statement block.
Variable Types
In JavaScript, there are seven primitive data types: boolean, number, string, undefined,
object, function, and symbol (symbol won’t be discussed). One thing that stands out
here is that undefined is a primitive value that is assigned to a variable that has just been
declared. typeof is the primitive operator used to return the type of a variable.
Truthy/Falsey Check
True/false checking is used in if statements. In many languages, the parameter inside
the if() function must be a boolean type. However, JavaScript (and other dynamically
typed languages) is more flexible with this. Here’s an example:
1 if(node){
2 ...
3 }
Here, node is some variable. If that variable is empty, null, or undefined, it will be
evaluated as false.
Here are commonly used expressions that evaluate to false:
• false
• 0
• undefined
• null
• true
• Non-empty strings
• Non-empty object
17
Chapter 2 JavaScript: Unique Parts
Here’s an example:
=== vs ==
JavaScript is a scripting language, and variables are not assigned a type during
declaration. Instead, types are interpreted as the code runs.
Hence, === is used to check equality more strictly than ==. === checks for both the
type and the value, while == checks only for the value.
"5" == 5 returns true because "5" is coerced to a number before the comparison.
On the other hand, "5" === 5 returns false because the type of "5" is a string, while 5 is
a number.
Objects
Most strongly typed languages such as Java use isEquals() to check whether two objects
are the same. You may be tempted to simply use the == operator to check whether two
objects are the same in JavaScript.
However, this will not evaluate to true.
1 var o1 = {};
2 var o2 = {};
3
4 o1 == o2 // returns false
5 o1 === o2 // returns false
18
Chapter 2 JavaScript: Unique Parts
Although these objects are equivalent (same properties and values), they are not
equal. Namely, the variables have different addresses in memory.
This is why most JavaScript applications use utility libraries such as lodash1 or
underscore,2 which have the isEqual(object1, object2) function to check two objects
or values strictly. This occurs via implementation of some property-based equality
checking where each property of the object is compared.
In this example, each property is compared to achieve an accurate object equality result.
1 function isEquivalent(a, b) {
2 // arrays of property names
3 var aProps = Object.getOwnPropertyNames(a);
4 var bProps = Object.getOwnPropertyNames(b);
5
6 // If their property lengths are different, they're different objects
7 if (aProps.length != bProps.length) {
8 return false;
9 }
10
11 for (var i = 0; i < aProps.length; i++) {
12 var propName = aProps[i];
13
14 // If the values of the property are different, not equal
15 if (a[propName] !== b[propName]) {
16 return false;
17 }
18 }
19
20 // If everything matched, correct
21 return true;
22 }
23 isEquivalent({'hi':12},{'hi':12}); // returns true
1
h ttps://lodash.com/
2
http://underscorejs.org/
19
Chapter 2 JavaScript: Unique Parts
However, this would still work for objects that have only a string or a number as the
property.
This is because functions and arrays cannot simply use the == operator to check for
equality.
Although the two functions perform the same operation, the functions have
different addresses in memory, and therefore the equality operator returns false.
The primitive equality check operators, == and ===, can be used only for strings and
numbers. To implement an equivalence check for objects, each property in the object
needs to be checked.
Summary
JavaScript has a different variable declaration technique than most programming
languages. var declares the variable within the function scope, let declares the variable
in the block scope, and variables can be declared without any operator in the global
scope; however, global scope should be avoided at all times. For type checking, typeof
should be used to validate the expected type. Finally, for equality checks, use == to check
the value, and use === to check for the type as well as the value. However, use these only
on non-object types such as numbers, strings, and booleans.
20
CHAPTER 3
JavaScript Numbers
This chapter will focus on JavaScript number operations, number representation, Number
objects, common number algorithms, and random number generation. By the end of
this chapter, you will understand how to work with numbers in JavaScript as well as how
to implement prime factorization, which is fundamental for encryption.
Number operations of a programming language allow you to compute numerical
values. Here are the number operators in JavaScript:
+ : addition
- : subtraction
/ : division
* : multiplication
% : modulus
These operators are universally used in other programming languages and are not
specific to JavaScript.
N
umber System
JavaScript uses a 32-bit floating-point representation for numbers, as shown in Figure 3-1.
In this example, the value is 0.15625. The sign bit (the 31st bit) indicates that the number
is negative if the sign bit is 1. The next 8 bits (the 30th to 23rd bits) indicate the exponent
value, e. Finally, the remaining 23 bits represent the fraction value.
æ 23
ö
value = ( -1) ´ 2e -127 ´ ç 1 + åb23 -t 2 -t ÷
sign
è t =1 ø
With decimal fractions, this floating-point number system causes some rounding
errors in JavaScript. For example, 0.1 and 0.2 cannot be represented precisely.
Hence, 0.1 + 0.2 === 0.3 yields false.
22
Chapter 3 JavaScript Numbers
Integer Rounding
Since JavaScript uses floating point to represent all numbers, integer division does not work.
Integer division in programming languages like Java simply evaluates division
expressions to their quotient.
For example, 5/4 is 1 in Java because the quotient is 1 (although there is a remainder
of 1 left). However, in JavaScript, it is a floating point.
1 5/4; // 1.25
23
Chapter 3 JavaScript Numbers
This is because Java requires you to explicitly type the integer as an integer.
Hence, the result cannot be a floating point. However, if JavaScript developers want to
implement integer division, they can do one of the following:
Math.floor(0.9); // 0
Math.floor(1.1); // 1
Math.round(0.49); // 0
Math.round(0.5); // 1
Math.round(2.9); // 3
Math.ceil(0.1); // 1 Math.ceil(0.9); // 1 Math.ceil(21);
// 21 Math.ceil(21.01); // 22
Number.EPSILON
Number.EPSILON returns the smallest interval between two representable numbers.
This is useful for the problem with floating-point approximation.
1 function numberEquals(x, y) {
2 return Math.abs(x - y) < Number.EPSILON;
3 }
4
5 numberEquals(0.1 + 0.2, 0.3); // true
This function works by checking whether the difference between the two numbers
are smaller than Number.EPSILON. Remember that Number.EPSILON is the smallest
difference between two representable numbers. The difference between 0.1+0.2 and 0.3
will be smaller than Number.EPSILON.
Maximums
Number.MAX_SAFE_INTEGER returns the largest integer.
24
Chapter 3 JavaScript Numbers
This returns true because it cannot go any higher. However, it does not work for
floating-point decimals.
1
Number.MAX_SAFE_INTEGER + 1.111 === Number.MAX_SAFE_INTEGER + 2.022;
// false
Minimums
Number.MIN_SAFE_INTEGER returns the smallest integer.
Number.MIN_SAFE_INTEGER is equal to -9007199254740991.
This returns true because it cannot get any smaller. However, it does not work for
floating-point decimals.
25
Chapter 3 JavaScript Numbers
Infinity
The only thing greater than Number.MAX_VALUE is Infinity, and the only thing smaller
than Number.MAX_SAFE_INTEGER is -Infinity.
Size Summary
This inequality summarizes the size of JavaScript numbers from smallest (left) to
largest (right):
Number Algorithms
One of the most discussed algorithms involving numbers is for testing whether a number
is a prime number. Let’s review this now.
Primality Test
A primality test can be done by iterating from 2 to n, checking whether modulus division
(remainder) is equal to zero.
1 function isPrime(n){
2 if (n <= 1) {
3 return false;
4 }
5
6 // check from 2 to n-1
7 for (var i=2; i<n; i++) {
8 if (n%i == 0) {
9 return false;
10 }
26
Chapter 3 JavaScript Numbers
11 }
12
13 return true;
14 }
2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97
This is difficult to notice, but all primes are of the form 6k ± 1, with the exception of
2 and 3 where k is some integer. Here’s an example:
Also realize that for testing the prime number n, the loop only has to test until the
square root of n. This is because if the square root of n is not a prime number, n is not a
prime number by mathematical definition.
1 function isPrime(n){
2 if (n <= 1) return false;
3 if (n <= 3) return true;
4
5 // This is checked so that we can skip
6 // middle five numbers in below loop
7 if (n%2 == 0 || n%3 == 0) return false;
8
9 for (var i=5; i*i<=n; i=i+6){
10 if (n%i == 0 || n%(i+2) == 0)
11 return false;
12 }
13
14 return true;
15 }
27
Chapter 3 JavaScript Numbers
P
rime Factorization
Another useful algorithm to understand is for determining prime factorization of a
number. Prime numbers are the basis of encryption (covered in Chapter 4) and hashing
(covered in Chapter 11), and prime factorization is the process of determining which
prime numbers multiply to a given number. Given 10, it would print 5 and 2.
1 function primeFactors(n){
2 // Print the number of 2s that divide n
3 while (n%2 == 0) {
4 console.log(2);
5 n = n/2;
6 }
7
8 // n must be odd at this point. So we can skip one element
(Note i = i +2)
9 for (var i = 3; i*i <= n; i = i+2) {
10 // While i divides n, print i and divide n
11 while (n%i == 0) {
12 console.log(i);
13 n = n/i;
14 }
15 }
16 //This condition is to handle the case when n is a prime number
17 //greater than 2
18 if (n > 2) {
19 console.log(n);
20 }
21 }
22 primeFactors(10); // prints '5' and '2'
28
Chapter 3 JavaScript Numbers
You may wonder how you get random integers or numbers greater than 1.
To get floating points higher than 1, simply multiply Math.random() by the range.
Add or subtract from it to set the base.
Exercises
1. Given three numbers x, y, and p, compute (xˆy) % p. (This is
modular exponentiation.)
Here, x is the base, y is exponent, and p is the modulus.
Modular exponentiation is a type of exponentiation performed
over a modulus, which is useful in computer science and used in
the field of public-key encryption algorithms.
At first, this problem seems simple. Calculating this is a one-line
solution, as shown here:
29
Chapter 3 JavaScript Numbers
c % m = (a b) % m
c % m = [(a % m) (b % m)] % m
4ˆ3 % 5 = 64 % 5 = 4
30
Chapter 3 JavaScript Numbers
value = (4 x 4) % 5 = 16 % 5 = 1
value = (1 x 4) % 5 = 4 % 5 = 4
1 function allPrimesLessThanN(n){
2 for (var i=0; i<n; i++) {
3 if (isPrime(i)){
4 console.log(i);
5 }
6 }
7 }
8
9 function isPrime(n){
10 if (n <= 1) return false;
11 if (n <= 3) return true;
12
31
Chapter 3 JavaScript Numbers
Let’s define ugly numbers as those whose only prime factors are
2, 3, or 5. The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, … shows the
first 11 ugly numbers. By convention, 1 is included.
To do this, divide the number by the divisors (2, 3, 5) until it
cannot be divided without a remainder. If the number can be
divided by all the divisors, it should be 1 after dividing everything.
Iterate this over n, and now the list of ugly numbers can be
returned.
33
Other documents randomly have
different content
—Mon premier, proposa Bel-Œil, est un métal précieux, mon second
un envoyé des cieux, mon tout un fruit délicieux: un baiser à qui
devinera ma charade!
—Jouons à la main chaude! opina Nougat:
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookball.com