Skip to main content

Posts

Showing posts with the label DSA

binary search Algorithm

Guide: Binary Search is used to find target integer in a sorted array quickly. Binary search has left , right , and mid variables, but the target variable is what binary search is used for. Assume num2 is a sorted array in which we are searching for target. The Match: If nums2[mid] is exactly equal to your target, you've found a common number! You can immediately return it. Go Right: If your target is greater than nums2[mid], that means your target has to be in the right half of nums2. Move your left pointer to mid + 1. Go Left: If your target is smaller than nums2[mid], your target must be in the left half. Move your right pointer to mid - 1. //java int left = 0; int right = nums2.length - 1; int mid = 0; int target = 0; while(left <= right) { mid = left + (right - left) / 2; if(nums1[i] == nums2[mid]) { return target; } else { if(target < nums2[mid]) { right = mid - 1; } else { ...

GCD Function

The greatest common divisor (GCD) is a fundamental concept in number theory, and its computation plays a crucial role in various mathematical and computational applications. In this comprehensive article, we will delve into the GCD function, exploring both recursive and non-recursive approaches, with a focus on Euclid’s division as an efficient method for GCD calculation. Recursive Approach: // A function to calculate the greatest common divisor of two positive integers int gcd ( int a, int b) { // If one of the numbers is zero, the other is the GCD if (a == 0 ) return b; if (b == 0 ) return a; // Use Euclid's algorithm to find the GCD recursively // The GCD of a and b is the same as the GCD of b and the remainder of a/b return gcd(b, a % b); } Non-Recursive Approach: // A non-recursive function to find the gcd of two positive integers int gcd ( int a, int b) { // Assume that a and b are positive // If not, convert them to positive by taking their a...