Let's walk through the Euclidean algorithm to find the GCD of
///////////////////////////////////////////////////
Explanation with the Function:
javascriptfunction gcd(a, b) {
while (b !== 0) {
let temp = b;
b = a % b;
a = temp;
}
return a;
}
function lcm(a, b) {
// Calculate the absolute values to handle negative numbers
let absA = Math.abs(a);
let absB = Math.abs(b);
// Calculate LCM using the formula: LCM(a, b) = abs(a * b) / GCD(a, b)
return Math.abs(absA * absB) / gcd(absA, absB);
}
// Example usage
console.log(lcm(12, 15))Key Points:
Base Case Check: The function starts by checking if is 0. If it is, it returns 1 because any number to the power of 0 is 1.
Negative Exponent Handling: If is negative, it calculates raised to the positive exponent and returns the reciprocal of that value.
Exponentiation by Squaring: This is where
let half = pow(x, Math.floor(n / 2));comes into play:- Explanation of
Math.floor(n / 2):Math.floor(n / 2)calculates the integer part of divided by 2. For example, if is 7,Math.floor(7 / 2)gives 3.- This is used to split the problem into two halves, approximately.
- Recursive Calculation:
let half = pow(x, Math.floor(n / 2));recursively calculates raised to the power of half of .- This reduces the problem size significantly compared to calculating raised to directly.
- Optimization:
- By calculating
half * half, the function squares the result ofpow(x, Math.floor(n / 2)). This step is possible because . - This approach reduces the number of recursive calls and improves efficiency.
- By calculating
- Explanation of
Odd Exponent Adjustment:
- If is odd (
n % 2 !== 0),result *= x;multipliesresultby to account for the remaining in .
- If is odd (
Example Execution:
If you call pow(2, 7), here's how it breaks down:
pow(2, 7)callspow(2, 3)(sinceMath.floor(7 / 2) = 3).pow(2, 3)callspow(2, 1).pow(2, 1)callspow(2, 0).
At pow(2, 0), it hits the base case and returns 1.
Then, it starts bubbling up the results:
pow(2, 1)returns .pow(2, 3)returns .pow(2, 7)returns .
This method effectively reduces the number of operations required to compute , making it more efficient than the straightforward recursive approach.
To find the first and last positions of target in the array [5, 7, 7, 10, 8] without sorting it again (assuming it's already sorted in non-decreasing order), we'll modify the searchRange function to handle the case where the array is already sorted. Here's how you can implement it:
javascriptfunction searchRange(nums, target) {
// Helper function to find the first occurrence
function findFirstOccurrence(nums, target) {
let left = 0;
let right = nums.length - 1;
let firstIdx = -1;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (nums[mid] === target && (mid === 0 || nums[mid - 1] < target)) {
// Found the first occurrence
return mid;
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return firstIdx;
}
// Helper function to find the last occurrence
function findLastOccurrence(nums, target) {
let left = 0;
let right = nums.length - 1;
let lastIdx = -1;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (nums[mid] === target && (mid === nums.length - 1 || nums[mid + 1] > target)) {
// Found the last occurrence
return mid;
} else if (nums[mid] > target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return lastIdx;
}
// Find first and last occurrence
let firstIdx = findFirstOccurrence(nums, target);
let lastIdx = findLastOccurrence(nums, target);
return [firstIdx, lastIdx];
}
// Example usage:
let nums = [5, 7, 7, 10, 8];
let target = 8;
let result = searchRange(nums, target);
console.log(`First and last position of ${target} in [${nums}]: [${result}]`);
Comments
Post a Comment