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 pdf download
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 pdf download
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-
made-easy-data-structure-and-algorithmic-puzzles-5th-edition-by-
careermonk-publications-narasimha-karumanchi-
isbn-9788193245279-15800/
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/
Data Structures and Algorithms in Java 1st Edition by Peter Drake ISBN
0131469142 9780131469143
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
Twelfth-Night, the last of Shakspeare's dramas, probable date
of, ii. 531-533.
Its general character, and conduct of the fable, 534.
U
Underdonne (Thomas), a minor poet of the age of Shakspeare,
i. 704.
Upstart country-squire or knight, character of, i. 81.
V
"Valentine and Orson," romance of, cited by Shakspeare, i. 572.
Notice of a curious edition of, 571, 572.
Its extensive popularity, 572.
Valentine's Day, origin of the superstitions concerning, i. 324.
Custom of choosing lovers ascribed to Madame Royale, 324,
325.
Supposed to be of pagan origin, 325.
Modes of ascertaining Valentines for the current year, 326.
The poor feasted on this day, 327.
Vallans (William), a minor poet of the age of Shakspeare, i. 705.
Vaughan's (W.) "Golden Grove," a collection of essays, i. 513.
Character of, with specimens of his style, 514.
Vaux (Lord), specimen of the poems of, i. 713.
Vennard (Richard), a minor poet of the age of Shakspeare, i.
705.
Venice one of the sources of English fashions in the age of
Shakspeare, ii. 94.
Venus and Adonis, a poem of Shakspeare, probable date of, i.
426, 427.
Notice of the "Editio Princeps," ii. 20, 21.
Dedicated to the Earl of Southampton, 3.
Proofs of its melody and beauty of versification, 21-23.
Singular force and beauty of its descriptions, 24-26.
Similes, 26.
And astonishing powers of Shakspeare's mind, 27.
This poem inferior to its classical prototypes, ibid.
Complimentary verses on this poem, addressed to
Shakspeare, 28-30.
Its meretricious tendency censured by contemporary writers,
31.
Popularity of this poem, 31. note [31:A].
Notice of its principal editions, 32.
Versification of the poetry of the Elizabethan age examined, i.
597.
Remarks on the versification of Sir John Beaumont, 601.
Of Browne, 603.
Of Chalkhill, 606.
Of Chapman, 608.
Of Daniel, 612.
Of Davies, 613.
Of Davors, 614.
Of Donne, 615.
Of Drayton, 616, 617.
Of Drummond, 618.
Of Fairefax, 619.
Of the two Fletchers, 620, 621.
Of Gascoigne, 626.
Of Bishop Hall, 628, 629.
Of Dr. Lodge, 632-635.
Of Marston, 637.
Of Spenser, 648.
Of the Earl of Stirling, 651.
Of Sylvester, 653.
Of Watson, 661.
Of Willobie, 665, 666.
Of Shakspeare's Venus and Adonis, ii. 21-23.
Of his Rape of Lucrece, 33-36.
Of Spenser's sonnets, 55.
Of Shakspeare's sonnets, 77-82.
Of Peele, 240. note.
Of the Two Gentlemen of Verona, 369.
Verstegan (Richard), a minor poet of the age of Shakspeare, i.
705.
Vincent (St.), supposed influence of his day, i. 350.
Virtue loved and cherished by Shakspeare's fairies, ii. 339, 340.
Virtus post funera vivit, whimsical translation of, i. 238, 239.
Voltaire's calumnies on Shakspeare refuted, ii. 553, 554.
Volumnia, remarks on the character of, ii. 494, 495.
Vortigern and Rowena, anecdote of, i. 127, 128.
Vows, how made by knights in the age of chivalry, i. 552.
Voyages and Travels, collections of, published in the time of
Shakspeare, i. 477-479.
W
Wager (Lewis), a dramatic poet, notice of, ii. 234.
Waists of great length, fashionable in the age of Shakspeare, ii.
97.
Wakes, origin of, i. 209.
Degenerate into licentiousness, 210.
Verses on, by Tusser, ibid.
And by Herrick, 211, 212.
Frequented by pedlars, 212.
Village-wakes still kept up in the North, 213.
Walton's "Complete Angler," errata in, i. 293. note.
Encomium on, 297. note.
Wapul (George), a dramatic writer in the time of Elizabeth, ii.
237.
Wardrobes (ancient), account of, ii. 91, 92.
Notice of theatrical wardrobes, in the time of Shakspeare,
220, 221.
Warner (William), biographical notice of, i. 658.
Critical remarks on his "Albion's England," 659, 660.
Quotations from that poem illustrative of old English
manners and customs, i. 104, 105. 118, 119. 135. 143. note.
147. note.
Warnings (preternatural) of death or danger, i. 351-354.
Warren (William), a minor poet of the age of Shakspeare, i. 705.
Warton (Dr.), observations of, on the "Gesta Romanorum," i.
536, 537.
On Fenton's collection of Italian novels, 542.
On the satires of Bishop Hall, 628, 629.
On the merits of Harington, 629.
On the satires of Marston, 637.
Washing of hands, why necessary before dinner in the age of
Elizabeth, ii. 145.
Wassail, origin of the term, i. 127.
Synonymous with feasting, 129.
Wassail-bowl, ingredients in, i. 127.
Description of an ancient one, 128.
Allusions to, in Shakspeare, 129, 130.
And by Milton, 131.
The peg-tankard, a species of wassail-bowl, 131. note.
Watch-lights, an article of furniture in Shakspeare's time, ii. 117.
Water-closets, by whom invented, ii. 135. note.
Water-spirits, different classes of, ii. 522, 523.
Watson (Thomas), a poet of the Elizabethan age, critical notice
of his works, particularly of his sonnets, i. 660-662., ii. 54.
Said by Mr. Steevens to be superior to Shakspeare as a
writer of sonnets, i. 663.
List of his other poems, ibid.
Weather, prognostications of, from particular days, i. 323.
Webbe (William), account of his "Discourse of English Poetrie,"
i. 463, 464.
Its extreme rarity and high price, 463. note.
First and second Eclogues of Virgil, 705.
Webster (William), a minor poet of the age of Shakspeare, i.
705.
Webster (John), estimate of the merits of, as a dramatic poet, ii.
564, 565.
Illustrations of his plays, viz.:
Vittoria Corombona, i. 233, 234. 237, 238. 396.
Dutchess of Malfy, i. 351.
Wedderburn, a minor poet of the age of Shakspeare, i. 705.
Weddings, how celebrated, i. 223-226.
Description of a rustic wedding, 227-229.
Weever (John), a minor poet of the age of Shakspeare, i. 705.
Bibliographical notice of his "Epigrammes," ii. 371.
Verses of, on Shakspeare's Venus and Adonis, ii. 28.
Epigram of, on Shakspeare's poems and plays, 372.
Wells, superstitious notions concerning, i. 391-393.
Wenman (Thomas), a minor poet of the age of Shakspeare, i.
706.
Wharton's "Dreame," a poem, i. 706.
Whetstone's (George), collection of tales, notice of, i. 543.
His "Rocke of Regard," and other poems, 706.
Account of the prevalence of gaming in his time, ii. 157, 158.
Notice of his dramatic productions, 238.
His "Promos and Cassandra," the immediate source of
Shakspeare's Measure for Measure, 453.
Whipping-tops anciently kept for public use, i. 312.
Whitney (George), a minor poet of the age of Shakspeare, i.
706.
Whitsuntide, festival of, how celebrated, i. 175-180.
Morris-dance, its accompaniment, ibid.
With Maid Marian, 179.
Whitsun plays, 181.
Wieland's "Oberon," character of, i. 564. note.
Wild-goose-chace, a kind of horse race, notice of, i. 304, 305.
Wilkinson (Edward), a minor poet of the age of Shakspeare, i.
706.
Will of John Shakspeare, account of the discovery of, i. 8, 9.
Copy of it, 9-14.
First published by Mr. Malone, ibid.
Its authenticity subsequently doubted by him, 15.
Confirmed by Mr. Chalmers, ibid.
Additional reasons for its authenticity, 16.
Its probable date, ibid.
Will of William Shakspeare, ii. 627-632.
Observations on it, 612-614.
Willet (Andrew), "Emblems" of, i. 706.
Willobie (Henry), a poet of the Elizabethan age, critical notice
of, i. 663, 664.
Origin of his "Avisa," 665.
Character of that work, 665, 666.
Commendatory verses in, on Shakspeare's Rape of Lucrece,
ii. 40.
Will-o'-wisp, superstitious notions concerning, i. 399, 400.
Willymat's (William) "Prince's Looking Glass," i. 706.
Wilmot (Robert), a dramatic poet in the reign of Elizabeth,
character of, ii. 234, 235.
Wilson (Thomas), observations of, on the corruptions of the
English language, in the time of James I., i. 440, 441.
Proofs that his "Rhetoricke" had been studied by
Shakspeare, 472-474.
Wincot ale celebrated for its strength, i. 48.
Epigram on, 48, 49.
Allusions to this place in Shakspeare's plays, 50.
Wine, enormous consumption of, in the age of Shakspeare, ii.
129.
Foreign wines then drunk, 130-132.
Presents of, usually sent from one room in a tavern to
another, 134.
Winter evening's conversations of the sixteenth century,
superstitious subjects of, i. 316-322.
Winter's Tale, probable date of, ii. 495-497.
Its general character, 497-500.
And probable source, 498.
Passages of this drama illustrated in the present work.
scene 3., i. 165. 181. 184. 212. 213. 582-584. ii. 499,
500.
Act v. scene 2., i. 584. ii. 499.
Y
Yates (James), "Castle of Courtesie," i. 707.
Yeomen. See Farmers.
Yong (Bartholomew), notice of his "Version of Montemayer's
Romance of Diana," i. 707. and note [707:C].
Yule-clog, or Christmas-block, i. 194.
Z
Zouche (Richard), notice of his "Dove," a geographical poem, i.
707.
THE END.
Printed by A. Strahan,
Printers-Street, London.
THE FOLLOWING WORKS
MAY ALSO BE HAD OF
T. CADELL AND W. DAVIES, STRAND.
TRANSCRIBER'S NOTES:
Pages vi and 626 are blank in the original.
Page numbers 332 and 333 are not used in the
original. A comparison with other editions of the
book shows that no text is missing. Page numbers
337 and 338 were used twice. The numbers have
been changed to 337a, 338a, 337b, and 338b.
There are two pages numbered 354 and no page
numbered 352. The first page 354 has been
renumbered to 352.
Corrections listed in the Errata have been
made.
In the Index, symbolic references to footnotes
have been replaced with the correct footnote
designation.
On page 223, there was a large white space
inside parentheses. The white space has been
replaced by four dashes.
If the images are not visible on page 519, the
first two are the symbol for Jupiter , and the
third is the symbol for Venus .
ebookball.com