# Python program to check if a number is negative or non-negative
number = float(input("Enter a number: ")) # Prompt user for input
# Check if the number is less than 0
if number < 0:
print("The number is negative.")
else:
print("The number is non-negative.")
Lesson 3.5.3 (Popcorn) - Python
- Hack: Check if a character is in the string ‘aeiou’ and print whether it is a vowel or not
# Python program to check if a character is a vowel
char = input("Enter a character: ") # Prompt user for input
# Check if the character is a vowel
if char in 'aeiou':
print(f"{char} is a vowel.")
else:
print(f"{char} is not a vowel.")
Lesson 3.5.4 (Popcorn) - JavaScript
- Hack: Use logical operators to identify if the inputted number is even or odd
%% js
<script>
// JavaScript program to check if a number is even or odd
let number = parseInt(prompt("Enter a number: ")); // Prompt user for input
// Check if the number is even or odd
if (number % 2 === 0) {
console.log(number + " is even.");
element.append(number + " is even.<br>");
} else {
console.log(number + " is odd.");
element.append(number + " is odd.<br>");
}
</script>
Lesson 3.5.3 (Main/Homework) - Python
- Hack: Greatest Common Divisor and Least Common Multiple
%%js
function gcdAndLcm(a, b) {
// Helper function to compute the GCD using Euclidean algorithm
function gcd(x, y) {
while (y !== 0) {
let temp = y;
y = x % y;
x = temp;
}
return x;
}
// Compute GCD
let gcdResult = gcd(a, b);
// Compute LCM
let lcmResult = (a * b) / gcdResult;
// Return the results as an object
return { GCD: gcdResult, LCM: lcmResult };
}
console.log(gcdAndLcm(24, 36)); // Output: { GCD: 12, LCM: 72 }
Lesson 3.5.4 (Main/Homework) - JavaScript
- Hack: Prime Factors
%% js
function primeFactors(n) {
let factors = [];
// Start dividing by 2
while (n % 2 === 0) {
factors.push(2);
n = n / 2;
}
// Try odd numbers from 3 onwards
for (let i = 3; i <= Math.sqrt(n); i += 2) {
while (n % i === 0) {
factors.push(i);
n = n / i;
}
}
// If n is still a prime number greater than 2
if (n > 2) {
factors.push(n);
}
return factors;
}
console.log(`Prime factors of 84 are: ${primeFactors(84)}`); // Output: [2, 2, 3, 7]