File tree Expand file tree Collapse file tree 2 files changed +20
-6
lines changed
Math/truncated_square_root Expand file tree Collapse file tree 2 files changed +20
-6
lines changed Original file line number Diff line number Diff line change 4
4
5
5
using namespace std ;
6
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
+
7
24
int main () {
8
- long long int n,x = 0 ,count= 0 ;
25
+ lli n ;
9
26
cout<<" Enter an integer: " <<endl;
10
27
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));
16
30
return 0 ;
17
31
}
You can’t perform that action at this time.
0 commit comments