Given a positive integer n. Find and return its square root. If n is not a perfect square, then return the floor value of sqrt(n).
Input: n = 36
Output: 6
Explanation: 6 is the square root of 36.
Input: n = 28
Output: 5
Explanation: The square root of 28 is approximately 5.292. So, the floor value will be 5.
Input: n=50
The idea here is to search for the floor of the square root of the given number linearly. For each number from 1 to the given number, find its square and check if it is smaller than the given number, if it is, store the current integer as potential root, else break out of the loop as the further calculations will only provide larger square roots.
ans
initialized to 0, which will eventually hold the floor of the square root of n.#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
/* Function to compute the floor of square root
of a given integer */
long long floorSqrt(long long n) {
long long ans = 0;
// Linear search in the answer space
for (long long i = 1; i <= n; i++) {
long long val = i * i;
// Check if val is less than or equal to n
if (val <= n * 1ll) {
ans = i; // Update ans to current value of i
} else {
break; // Exit loop if val exceeds n
}
}
// Return the computed floor of square root
return ans;
}
};
int main() {
int n = 28;
// Create an object of the Solution class
Solution sol;
int ans = sol.floorSqrt(n);
// Print the result
cout << "The floor of square root of " << n
<< " is: " << ans << "\n";
return 0;
}
class Solution {
/* Function to compute the floor of
square root of a given integer */
public long floorSqrt(long n) {
long ans = 0;
// Linear search in the answer space
for (long i = 1; i <= n; i++) {
long val = i * i;
// Check if val is less than or equal to n
if (val <= (long) n) {
// Update ans to current value of i
ans = (int) i;
}
else {
break;
}
}
// Return the computed floor of square root
return ans;
}
public static void main(String[] args) {
int n = 28;
// Create an object of the Solution class
Solution sol = new Solution();
int ans = sol.floorSqrt(n);
// Print the result
System.out.println("The floor of square root of " + n
+ " is: " + ans);
}
}
class Solution:
""" Function to compute the floor of
square root of a given integer """
def floorSqrt(self, n: int) -> int:
ans = 0
# Linear search in the answer space
for i in range(1, n + 1):
val = i * i
# Check if val is less than or equal to n
if val <= n:
# Update ans to current value of i
ans = i
else:
break
# Return the computed floor of square root
return ans
if __name__ == "__main__":
n = 28
# Create an object of the Solution class
sol = Solution()
ans = sol.floorSqrt(n)
# Print the result
print(f"The floor of square root of {n} is: {ans}")
class Solution {
/* Function to compute the floor of
square root of a given integer */
floorSqrt(n) {
let ans = 0;
// Linear search in the answer space
for (let i = 1; i <= n; i++) {
let val = i * i;
// Check if val is less than or equal to n
if (val <= n) {
// Update ans to current value of i
ans = i;
}
else {
break;
}
}
// Return the computed floor of square root
return ans;
}
}
// Main function to test the floorSqrt method
let n = 28;
// Create an object of the Solution class
let sol = new Solution();
let ans = sol.floorSqrt(n);
// Print the result
console.log(`The floor of square root of ${n} is: ${ans}`);
Binary Search algorithm can be used to optimize the brute force solution. While applying the binary search algorithm, compare the square of mid with the given number, if the square is less than or equal to the given number, store the mid as it can be a potential root and eliminate the left half of the search space, else eliminate the right half.
low
to 1 and high
initialized to n, where n is the given number, defining the search range for ans. Also, initialize ans
to 0 to store the answer.val
as mid * mid, the square of the midpoint.#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
/* Function to compute the floor of
square root of a given integer */
long long floorSqrt(long long n) {
long long low = 1, high = n;
// Binary search on the answer space
while (low <= high) {
long long mid = (low + high) / 2;
long long val = mid * mid;
// Check if val is less than or equal to n
if (val <= (long long)(n)) {
// Move to the right part
low = mid + 1;
} else {
// Move to the left part
high = mid - 1;
}
}
// Return the floor of square root
return high;
}
};
int main() {
int n = 28;
// Create an object of the Solution class
Solution sol;
int ans = sol.floorSqrt(n);
// Print the result
cout << "The floor of square root of " << n
<< " is: " << ans << "\n";
return 0;
}
class Solution {
/* Function to compute the floor of
square root of a given integer */
public long floorSqrt(long n) {
long low = 1, high = n;
// Binary search on the answer space
while (low <= high) {
long mid = (long)(low + high) / 2;
long val = mid * mid;
// Check if val is less than or equal to n
if (val <= (long)(n)) {
// Move to the right part
low = (int)(mid + 1);
} else {
// Move to the left part
high = (int)(mid - 1);
}
}
// Return the floor of square root
return high;
}
public static void main(String[] args) {
int n = 28;
// Create an object of the Solution class
Solution sol = new Solution();
int ans = sol.floorSqrt(n);
// Print the result
System.out.println("The floor of square root of " + n + " is: " + ans);
}
}
class Solution:
""" Function to compute the floor of
square root of a given integer """
def floorSqrt(self, n: int) -> int:
low, high = 1, n
# Binary search on the answer space
while low <= high:
mid = (low + high) // 2
val = mid * mid
# Check if val is less than or equal to n
if val <= n:
# Move to the right part
low = mid + 1
else:
# Move to the left part
high = mid - 1
# Return the floor of square root
return high
if __name__ == "__main__":
n = 28
# Create an object of the Solution class
sol = Solution()
ans = sol.floorSqrt(n)
# Print the result
print(f"The floor of square root of {n} is: {ans}")
class Solution {
/* Function to compute the floor of
square root of a given integer */
floorSqrt(n) {
let low = 1, high = n;
// Binary search on the answer space
while (low <= high) {
let mid = Math.floor((low + high) / 2);
let val = mid * mid;
// Check if val is less than or equal to n
if (val <= n) {
// Move to the right part
low = mid + 1;
} else {
// Move to the left part
high = mid - 1;
}
}
// Return the floor of square root
return high;
}
}
// Main function to test the solution
let n = 28;
// Create an object of the Solution class
let sol = new Solution();
let ans = sol.floorSqrt(n);
// Print the result
console.log(`The floor of square root of ${n} is: ${ans}`);
Q: How do we avoid integer overflow when computing mid^2?
A: Instead of directly calculating mid^2, compare mid with n/mid. If mid > n / mid, mid^2 exceeds n, and you should move left. This ensures safe arithmetic even for large n.
Q: What happens if n is a perfect square?
A: The binary search naturally finds the exact square root when mid^2 == n. The result is returned directly without additional steps.
Q: What if the function needs to work in real-time systems?
A: Use approximation techniques like Newton’s method, which converges quickly and is well-suited for systems requiring rapid results.
Q: How would you compute the square root for floating-point numbers?
A: For floating-point numbers, extend the binary search to calculate the square root up to a desired precision (ϵ): Continue the search until ∣mid^2−n∣<ϵ. Update low and high with smaller increments as the range narrows.