### Lesson 3.3.1 - 2 Popcorn hacks and 4 Homework hacks
# python hack 3
n= int(input())
total_sum = 0
for i in range(1, n + 1):
total_sum += i
print(total_sum)
3
%%js
//Javascript hack 1
function calculate() {
let result = (8 * 4) - 5 + (10 / 2);
return result;
}
console.log(calculate());
32
<IPython.core.display.Javascript object>
%%js
//Javascript Homework Hack 1
function gcdLcm(a, b) {
let gcd = function(x, y) {
while (y !== 0) {
let temp = y;
y = x % y;
x = temp;
}
return x;
};
const gcdValue = gcd(a, b);
const lcmValue = (a * b) / gcdValue; // LCM formula
return { GCD: gcdValue, LCM: lcmValue };
}
const result = gcdLcm(12, 15);
console.log(result); // { GCD: 3, LCM: 60 }
<IPython.core.display.Javascript object>
%%js
//Javascript Homework Hack 2
function primeFactors(n) {
const factors = [];
while (n % 2 === 0) {
factors.push(2);
n /= 2;
}
for (let i = 3; i <= Math.sqrt(n); i += 2) {
while (n % i === 0) {
factors.push(i);
n /= i;
}
}
if (n > 2) {
factors.push(n);
}
return factors;
}
// Example usage
const testNumber = 28;
const result = primeFactors(testNumber);
console.log(result); // Output: [2, 2, 7]
<IPython.core.display.Javascript object>
# Python Homework Hack 1
def calculate_mean_and_median(numbers):
mean = sum(numbers) / len(numbers)
sorted_numbers = sorted(numbers)
n = len(sorted_numbers)
mid = n // 2
median = (sorted_numbers[mid] if n % 2 != 0 else (sorted_numbers[mid - 1] + sorted_numbers[mid]) / 2)
print("Mean:", mean)
print("Median:", median)
numbers = [4, 8, 15, 16, 23, 42]
calculate_mean_and_median(numbers)
Mean: 18.0
Median: 15.5
# Python Homework Hack 2
def collatz_sequence(a):
sequence = []
while a != 1:
sequence.append(a)
if a % 2 == 0:
a = a // 2
else:
a = 3 * a + 1
sequence.append(1)
return sequence
test_value = 6
output = collatz_sequence(test_value)
print(output)
[6, 3, 10, 5, 16, 8, 4, 2, 1]