Fall 2024 - P4
Big Idea 3 | .1 | .2 | .3 | .4 | .5 | .6 | .7 | .8 | .10 |
3.3 Javascript Mathematical Hacks
Student led teaching on Mathematical Expressions. Learn how mathematical expressions involve using arithmetic operators (like addition, subtraction, multiplication, and division) to perform calculations
Popcorn Hacks
- Easy
- Create a function that uses 4 of the 5 basic arithmetic operations and returns the number 32 as the answer.
- Medium
- Make a function that lets you make a sandwich. Ask for different ingredients and at the end give the sandwich a name.
- Hard
- Create a “choose-your-own-path” type of game. There should be 2-3 different storylines the user can choose from (Ex: You see a fight at school. Do you break it up or mind your own buiness.)
- BONUS: draw a flowchart for your code.
Example Hack 1 (Function for Basic Arithmetic Operations)
%%javascript
function basicOperations(a, b) {
let sum = a + b;
let difference = a - b;
let product = a * b;
let quotient = a / b;
let remainder = a % b;
console.log(`Addition: ${a} + ${b} = ${sum}`);
console.log(`Subtraction: ${a} - ${b} = ${difference}`);
console.log(`Multiplication: ${a} * ${b} = ${product}`);
console.log(`Division: ${a} / ${b} = ${quotient}`);
console.log(`Modulus: ${a} % ${b} = ${remainder}`);
}
basicOperations(10, 5);
Example Hack 2 (Fibbonaci Sequence)
function fibonacci(n) {
if (n === 0) return 0;
if (n === 1) return 1;
let a = 0;
let b = 1;
let next;
for (let i = 2; i <= n; i++) {
next = a + b;
a = b;
b = next;
}
return b;
}
let n = 7; // Find the 7th Fibonacci number
console.log(`The ${n}th Fibonacci number is: ${fibonacci(n)}`);
Homework Hacks
After learning about Mathmatical Expressions and Operations in JavaScript, you should be able to complete the hacks listed below…
- Write a function that takes two variables a and b. The function should:
- Compute the Greatest Common Divisor (GCD) of a and b.
- Compute the Least Common Multiple (LCM) of a and b.
- Return both results as an object.
- Write a function that takes a positive integer n and returns an array of its prime factors. Prime factors are the prime numbers that divide n exactly, without leaving a remainder. If n is a prime number, the array should simply contain n.