Write a program to find the square root of the given number.
Example 1:
Input: x = 4
Output: 2
Example 2:
Input: x = 8
Output: 2 (Truncated the decimal point value)
Approach 1:
Java
public class SqrtNumber {public static void main(String[] args) {int x = 2147395600;System.out.println(sqrtUsingBinarySearch(x));}private static int sqrtUsingBinarySearch(int x) {if (x <= 1)return x;long low = 1l;long high = x / 2;long mid = 0l;while (low <= high) {mid = low + (high - low) / 2;if (mid * mid < x) {low = low + 1;} else if (mid * mid > x) {high = mid - 1;} elsereturn (int) mid;}return (int) (--low);}//Time Complexity : O(log(n))
C++
#include <bits/stdc++.h>using namespace std;//Function to find sqrt(n)long long int sqrtNum(long long int n){long long int low=1,high=n;while(low<=high){long long int mid=low+(high-low)/2;if(mid*mid==n)return mid;else if(mid*mid>n)high=mid-1;elselow=mid+1;}return --low;}int main(){long long int n=2147395600;long long int ans=sqrtNum(n);cout<<"sqrt of "<<n<<" is "<<ans<<"\n";return 0;}//Time Complexity: O(log(n));//Space Complexity:O(1)
Approach 2:
Java
public class SqrtNumber {public static void main(String[] args) {int x = 2147395600;System.out.println(sqrt(x));}private static int sqrt(int n) {long i;for (i = 1; i * i <= n; i++) {}return (int) --i;}}//Time Complexity : O(Sqrt(n))
C++
#include <bits/stdc++.h>using namespace std;//Function to find sqrt(n)long long int sqrtNum(long long int n){long long int i;for(i=1;i*i<=n;i++){}return (int)--i;}int main(){long long int n=2147395600;long long int ans=sqrtNum(n);cout<<"sqrt of "<<n<<" is "<<ans<<"\n";return 0;}//Time Complexity: O(sqrt(n));//Space Complexity:O(1)
No comments:
Post a Comment