Skip to the content.

Lessons 3.3 Hacks

3.3

Popcorn Hacks

3.3.3 Python Mathematical Hacks

Hack 3

  1. Prompt the user to enter a number n.
  2. Initialize total_sum to 0.
  3. Use a loop to iterate from 1 to n.
  4. Add each number to total_sum.
  5. Print the total_sum.
# ask user for int input
print("Please input a whole number")
n = int(input())

total_sum = 0

# iterate through values
for i in range (1, n +1):
        total_sum += i
print("The sum of", n, "and every integer before it is", total_sum)
Please input a whole number
The sum of 3 and every integer before it is 6

3.3.4 Javascript Mathematical Hacks

Hack 1: Easy

Create a function that uses 4 of the 5 basic arithmetic operations and returns the number 32 as the answer.

%%html

<script>
let a = 5
let b = 10

let c = ((((a + b) * 20) / 10) + 10) - 8;
console.log("c =", c);
console.log(c, "is equal to 32");
</script>

Hacks

3.3.3 Python Mathematical Hacks

Hack 1

Compute the arithmetic mean and median and print both results.

list = [12, 17, 14, 12, 15, 18, 9]

def findMean():
    list_sum = sum(list)
    global list_num1
    list_num1 = len(list)
    mean = list_sum/list_num1
    mean = round(mean, 2) # round to 2 decimal places
    print()
    print("The arithmetic mean is approximately", mean)
   
   
def findMedian():
    list.sort()
    if list_num1 % 2==0:
        median = (list[list_num1//2 - 1] + list[list_num1//2]) / 2
    else:
        median = list[list_num1//2]
    print()
    print("The median is", median)
     
print("The initial values are", list)     
findMean()
findMedian()
The initial values are [12, 17, 14, 12, 15, 18, 9]

The arithmetic mean is approximately 13.86

The median is 14

Alternate hack: Compute the arithmetic mean and median from a user-inputted list

def getList():
    global num_list
    num_list = input("Please input a list of whole numbers seperated with commas:")
    num_list = num_list.split(',') # splits the input into a list
    num_list = [int(num) for num in num_list] # turns string into integers
    print("You have inputted", num_list)

getList()

def findMean():
    list_sum = sum(num_list)
    global list_num2
    list_num2 = len(num_list)
    mean = list_sum/list_num2
    mean = round(mean, 2) # round to 2 decimal points
    print()
    print("The arithmetic mean is approximately", mean)
    
def findMedian():
    num_list.sort()
    if list_num2 % 2==0:
        median = (num_list[list_num2//2 - 1] + num_list[list_num2//2]) / 2
    else:
        median = num_list[list_num2//2]
    print()
    print("The median is", median)

    
findMean()
findMedian()
You have inputted [1, 3, 4, 5, 6, 7]

The arithmetic mean is approximately 4.33

The median is 4.5

Hack 2

Make a function that lists numbers in the Collatz Problem.

print("Welcome to the Collatz Problem. Let's begin with an integer to start us off.")

global a
a = int(input("Please input an integer:"))
print("You have inputted", a)

collatz_list = [a]

def collatz(a):
    if a % 2 == 0:
        global b
        b = a//2
    else:
        b = (3*a)+1
    print(b)
    return(b)
    
def collatz_sequence(a):
    while a!=1:
        a=collatz(a)
        collatz_list.append(a)
    return collatz_list
        
print("The Collatz sequence starting from the inputted value", a, "is", collatz_sequence(a))
Welcome to the Collatz Problem. Let's begin with an integer to start us off.
You have inputted 5
16
8
4
2
1
The Collatz sequence starting from the inputted value 5 is [5, 16, 8, 4, 2, 1]

3.3.4 Javascript Mathematical Hacks

Hack 1

Compute the GCD and LCM and return both results as an object

%%html
<script>
let a = 6
let b = 8

function findLCM(a,b){
    let large = Math.max(a,b);
    let small = Math.min(a,b);
    for (i = large; ; i+=large){
        if (i % small == 0) 
            return i; 
    }
}

function findGCD(a,b){
    if (b === 0) {
        return a;
    }
    return findGCD(b, a % b);
}

console.log("The GCD of " + a + " and " +  b + " is " + findGCD(a, b) + "\n");
console.log("The LCM of " + a + " and " +  b + " is " + findLCM(a, b) + "\n");
console.log(findGCD(a, b), ",", findLCM(a, b))
</script>

Alternate hack: Compute the GCD and LCM based on user-inputted values and return both results as an object

%%html
<script>

console.log("Enter two integers to begin"+"\n")

//get user input
function getValues(a,b){
    x = prompt("Please enter the first number to calculate GCD and LCM");
    y = prompt("Please enter the second number");
}

getValues()

//turn strings to integers
a = parseInt(x);
b = parseInt(y);

function findLCM(a,b){
    let large = Math.max(a,b);
    let small = Math.min(a,b);
    for (i = large; ; i+=large){
        if (i % small == 0) 
            return i; 
    }
}

function findGCD(a,b){
    if (b === 0) {
        return a;
    }
    return findGCD(b, a % b);
}

console.log("The GCD of " + a + " and " +  b + " is " + findGCD(a, b) + "\n");
console.log("The LCM of " + a + " and " +  b + " is " + findLCM(a, b) + "\n");
console.log(findGCD(a, b), ",", findLCM(a, b))
</script>

Hack 2

Write a function that returns a number’s prime factors

%%html
<script>

var n = 24;
const primeFactorization = [];

function findFactors(n){
    while (n>=2){
        if (n % 2 == 0){
            primeFactorization.push(2);
            n = n/2;
        }else{
            for (let i = 3; i <= Math.sqrt(n); i += 2) {
                while (n % i == 0) {
                    primeFactorization.push(i);
                    n = n / i;
                }
            }
            if (n > 2) {
                primeFactorization.push(n);
                break;
            }
        }
    }
    return primeFactorization
}

console.log("The prime factorization of", n, "is", findFactors(n))
</script>

Alternate hack: Write a function that returns a user-inputted number’s prime factors

%%html
<script>

var input = prompt("Please enter a number to find the prime factorization for");
n = parseInt(input);
const primeFactorization2 = [];

function findFactors(n){
    while (n>=2){
        if (n % 2 == 0){
            primeFactorization2.push(2);
            n = n/2;
        }else{
            for (let i = 3; i <= Math.sqrt(n); i += 2) {
                while (n % i == 0) {
                    primeFactorization2.push(i);
                    n = n / i;
                }
            }
            if (n > 2) {
                primeFactorization2.push(n);
                break;
            }
        }
    }
    return primeFactorization2
}

console.log("The prime factorization of", n, "is", findFactors(n))
</script>