Skip to content

Instantly share code, notes, and snippets.

@jatinsharrma
Created May 16, 2021 08:51
Show Gist options
  • Save jatinsharrma/df7cf1d15855589fcb5eec2e1a9faea2 to your computer and use it in GitHub Desktop.
Save jatinsharrma/df7cf1d15855589fcb5eec2e1a9faea2 to your computer and use it in GitHub Desktop.
Square Root | C++ | Long Division Method
//This only take int data type and input.
//More inprovment can be done, example in helper we can use binary search.
#include <iostream>
#include <vector>
std::vector<int> getPairs(int num)
{
std::vector<int> pairs;
while(num){
int temp=0;
temp += num%100;
num /= 100;
pairs.insert(pairs.begin(),temp);
}
return pairs;
}
void helper(int& divident, int& divisor, int& mid_term, int& sqrt)
{
for(auto j=1;j<=10;j++){
int temp_divisor = divisor + j;
mid_term = temp_divisor*j;
if(mid_term > divident){
mid_term = (temp_divisor-1) * (j -1);
sqrt = sqrt*10+j-1;
divisor = temp_divisor + j -2;
break;
}
else if(mid_term == divident){
divisor = temp_divisor+j;
sqrt = sqrt*10 +j;
break;
}
}
}
int squareRoot(int num)
{
std::vector<int> pairs = getPairs(num);
int sqrt = 0;
int divisor = 0;
int divident = 0;
for(auto i=0;i<pairs.size();i++){
divident += pairs[i];
int mid_term = 0 ;
helper(divident,divisor,mid_term,sqrt);
//std::cout << divisor <<" " << divident<<" "<<mid_term <<'\n';
divisor *=10;
divident = (divident-mid_term)*100;
}
return sqrt;
}
int main()
{
int t=0;
std::cin >> t;
while(t--){
int num=0;
std::cin >> num;
std::cout << squareRoot(num) << '\n';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment