Skip to content

Commit 2314332

Browse files
committed
truncated_square_root.cpp: Used binary search
Used binary search for root. Used bit manipulation instead of division.
1 parent c6b657a commit 2314332

File tree

2 files changed

+20
-6
lines changed

2 files changed

+20
-6
lines changed

Math/truncated_square_root/a.out

48 Bytes
Binary file not shown.

Math/truncated_square_root/truncated_square_root.cpp

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,28 @@
44

55
using namespace std;
66

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+
724
int main() {
8-
long long int n,x = 0,count=0;
25+
lli n;
926
cout<<"Enter an integer: "<<endl;
1027
cin>>n;
11-
for(int i = 1;x <= n;i += 2) {
12-
x += i;
13-
count++;
14-
}
15-
printf("Square root of %lld is: %lld\n",n,count-1);
28+
if (n < 0) return 0;
29+
printf("Square root of %lld is: %lld\n",n,flrSqrt(n));
1630
return 0;
1731
}

0 commit comments

Comments
 (0)