Snippets Collections
// Efficient Code

import java.util.*;
import java.io.*;

class GFG 
{ 
	static int sqRootFloor(int x)
	{
		int low = 1, high = x, ans = -1;

		while(low <= high)
		{
			int mid = (low + high) / 2;

			int mSq = mid * mid;

			if(mSq == x)
				return mid;
			else if(mSq > x)
				high = mid - 1;
			else
			{
				low = mid + 1;
				ans = mid;
			}
		}

		return ans;
	}

	public static void main(String args[]) 
    {

		System.out.println(sqRootFloor(10));

    } 

}





// Naive Code

import java.util.*;
import java.io.*;

class GFG 
{ 
	static int sqRootFloor(int x)
	{
		int i = 1;

		while(i * i <= x)
			i++;

		return i - 1;
	}

	public static void main(String args[]) 
    {

		System.out.println(sqRootFloor(15));

    } 

}
star

Tue Feb 08 2022 13:42:51 GMT+0000 (Coordinated Universal Time)

#java #gfg #geeksforgeeks #lecture #searching #squareroot

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension