Skip to content

Commit e5bf4b3

Browse files
Merge pull request matthewsamuel95#189 from mouri11/master
truncated_square_root.cpp: Used binary search to find square root
2 parents 2fa3499 + 2314332 commit e5bf4b3

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

Math/truncated_square_root/a.out

13 KB
Binary file not shown.
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#include <iostream>
2+
#include <cstdio>
3+
#include <cstdlib>
4+
5+
using namespace std;
6+
7+
typedef long long int lli;
8+
9+
lli flrSqrt(lli n) { // using binary search to calculate square root
10+
if (n == 0 || n == 1) return n;
11+
lli start = 0, end = n/2, ans;
12+
while (start <= end) {
13+
lli mid = (start + end) >> 1;
14+
if (mid*mid == n) return mid;
15+
else if (mid*mid < n) {
16+
start = mid + 1;
17+
ans = mid;
18+
}
19+
else end = mid - 1;
20+
}
21+
return ans;
22+
}
23+
24+
int main() {
25+
lli n;
26+
cout<<"Enter an integer: "<<endl;
27+
cin>>n;
28+
if (n < 0) return 0;
29+
printf("Square root of %lld is: %lld\n",n,flrSqrt(n));
30+
return 0;
31+
}

0 commit comments

Comments
 (0)