Big Idea 3 Section 3

Popcorn Hack #1

number1 = 21
number2 = 2

Addition_var = number1 + number2
Subtract_var = number1 - number2
Multiply_var = number1 * number2
Divide_var = number1 / number2 if number2 != 0 else 'undefined'

print(f"Numbers added: {Addition_var}")
print(f"Numbers subtracted: {Subtract_var}")
print(f"Numbers multiplied: {Multiply_var}")
print(f"Numbers divided: {Divide_var}")
Numbers added: 23
Numbers subtracted: 19
Numbers multiplied: 42
Numbers divided: 10.5

Popcorn Hack #2

def fibonacci_algorithm(num):
    if num <= 0:
        return "This input is invalid, please try something else."
    elif num == 1:
        return 0
    elif num == 2:
        return 1
    else:
        return fibonacci_algorithm(num - 1) + fibonacci_algorithm(num - 2)


num = 23
print(f"The {num}th Fibonacci number is: {fibonacci_algorithm(num)}")
The 23th Fibonacci number is: 17711

Homework in Python

import numpy as np
import logging
import sys

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(levelname)s:%(message)s')

def matrix_multiply(A, B):
    """
    Perform matrix multiplication between two numpy arrays A and B.
    """
    logging.debug(f"Multiplying matrices:\n{A}\n{B}")
    return np.dot(A, B)

def matrix_power(M, power):
    """
    Raise matrix M to the specified power using binary exponentiation.
    """
    if power < 0:
        raise ValueError("Power must be a non-negative integer.")
    
    result = np.identity(len(M), dtype=object)
    logging.debug(f"Initial identity matrix:\n{result}")
    
    while power > 0:
        if power % 2 == 1:
            result = matrix_multiply(result, M)
            logging.debug(f"Result after multiplying by M:\n{result}")
        M = matrix_multiply(M, M)
        logging.debug(f"Matrix M squared:\n{M}")
        power = power // 2
        logging.debug(f"Power reduced to: {power}")
    
    return result

def fibonacci_matrix(n):
    """
    Calculate the nth Fibonacci number using matrix exponentiation.
    """
    if not isinstance(n, int):
        raise TypeError("Input must be an integer.")
    if n < 0:
        raise ValueError("Fibonacci number is not defined for negative integers.")
    elif n == 0:
        return 0
    elif n == 1:
        return 1
    
    F = np.array([[1, 1],
                  [1, 0]], dtype=object)
    
    result = matrix_power(F, n-1)
    
    logging.info(f"Matrix raised to power {n-1}:\n{result}")
    
    return result[0][0]

def validate_input(user_input):
    """
    Validate the user input to ensure it's a non-negative integer.
    """
    try:
        value = int(user_input)
        if value < 0:
            raise ValueError
        return value
    except ValueError:
        raise ValueError("Please enter a valid non-negative integer.")

def main():
    """
    Main function to execute the Fibonacci calculation.
    """
    try:
        user_input = input("Enter the position of the Fibonacci number you want to calculate: ")
        n = validate_input(user_input)
        fib_n = fibonacci_matrix(n)
        print(f"Fibonacci number at position {n} is: {fib_n}")
    except ValueError as ve:
        logging.error(ve)
    except Exception as e:
        logging.error(f"An unexpected error occurred: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()

Homework in Javascript

%%js

function fibonacci(n) {
    if (n === 0) return 0;
    if (n === 1) return 1;

    let prev1 = 1, prev2 = 0, current = 0;

    for (let i = 2; i <= n; i++) {
        current = prev1 + prev2;
        prev2 = prev1;
        prev1 = current;
    }

    return current;
}

function fibonacciMatrix(n) {
    if (n === 0) return 0;
    
    let F = [[1, 1], [1, 0]];
    power(F, n - 1);

    return F[0][0];
}

function power(F, n) {
    if (n === 0 || n === 1) return;

    let M = [[1, 1], [1, 0]];

    power(F, Math.floor(n / 2));
    multiply(F, F);

    if (n % 2 !== 0) multiply(F, M);
}

function multiply(F, M) {
    let x = F[0][0] * M[0][0] + F[0][1] * M[1][0];
    let y = F[0][0] * M[0][1] + F[0][1] * M[1][1];
    let z = F[1][0] * M[0][0] + F[1][1] * M[1][0];
    let w = F[1][0] * M[0][1] + F[1][1] * M[1][1];

    F[0][0] = x;
    F[0][1] = y;
    F[1][0] = z;
    F[1][1] = w;
}

let n = 50;

console.log("Fibonacci number at position " + n + " using DP is: " + fibonacci(n));
console.log("Fibonacci number at position " + n + " using Matrix Exponentiation is: " + fibonacciMatrix(n));

<IPython.core.display.Javascript object>