Rhea Rajashekhar P4 Popcorn Hacks 3.3

# Popcorn Hack 1: Prompt the user to enter a number n. Initialize total_sum to 0. Use a loop to iterate from 1 to n. Add each number to total_sum. Print the total_sum. (Python)

# Function to get valid integer input
def get_integer_input():
    while True:
        try:
            n = int(input("Please enter a positive integer: "))
            if n > 0:  # Ensure the number is positive
                return n
            else:
                print("Please enter a positive integer.")
        except ValueError:
            print("Invalid input. Please enter a valid integer.")

# Get a valid number from the user
n = get_integer_input()

# Initialize total_sum to 0
total_sum = sum(range(1, n + 1))  # Using sum and range for a concise approach

# Print the total_sum
print("The total sum from 1 to", n, "is:", total_sum)
# Homework Hack 1: Compute mean and median
import statistics

def compute_statistics(numbers):
    mean = statistics.mean(numbers)
    median = statistics.median(numbers)
    print(f"Arithmetic Mean: {mean}")
    print(f"Median: {median}")

# Example usage
data = [10, 20, 30, 40, 50]
compute_statistics(data)

# Function for the Collatz sequence
def collatz_sequence(start):
    sequence = [start]
    while start != 1:
        start = start // 2 if start % 2 == 0 else 3 * start + 1
        sequence.append(start)
    print("Collatz sequence:", sequence)

# Example usage
collatz_sequence(13)

%% js 
// Popcorn Hack 2: Create a function that uses 4 of the 5 basic arithmetic operations and returns the number 32 as the answer. (JavaScript)
function computeThirtyTwo() {
    // Using four arithmetic operations: +, -, *, /
    let result = (8 * 5) - (4 / 2) + 6; // 8*5 = 40, 4/2 = 2, 40 - 2 + 6 = 44
    result -= 12; // Final adjustment to get 32
    return result;
}

// Call the function and log the result
console.log(computeThirtyTwo()); // Output: 32
%% js 
// Homework Hack 2: Compute GCD and LCM
function calculateGCDAndLCM(x, y) {
    // Helper function to compute GCD using the Euclidean algorithm
    function findGCD(a, b) {
        while (b !== 0) {
            let temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }
    
    let gcdValue = findGCD(x, y);
    let lcmValue = Math.abs(x * y) / gcdValue;
    
    return {
        gcd: gcdValue,
        lcm: lcmValue
    };
}

// Example usage
console.log(calculateGCDAndLCM(12, 18)); // Output: { gcd: 6, lcm: 36 }