-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathGFG_TripletSum.cpp
130 lines (103 loc) · 2.49 KB
/
GFG_TripletSum.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
/*
https://practice.geeksforgeeks.org/problems/triplet-sum-in-array-1587115621/1
Triplet Sum in Array
*/
// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// Function to find square root
// x: element to find square root
class Solution{
public:
int x;
long long int floorSqrt(long long int x)
{
// Your code goes here
if(x==0 || x ==1) return x;
// /**** Recursive Binary Search ******/
// this->x = x;
// return SqrtRec(1, x/2 );
/**** Linear Binary Search ******/
unsigned int i=1, j = x/2, mid=-1;
int ans=-1;
while(i<=j){
mid = i + (j-i)/2;
if(mid == x/mid)
return mid;
if(mid < x/mid)
{
i=mid+1;
}
else{
j=mid-1;
}
}
return j;
}
long long int SqrtRec(long long int i, long long int j)
{
if(i>j) return j;
int mid = i + (j-i)/2;
if(mid == x/mid) return mid;
if (mid<x/mid) return SqrtRec(mid+1, j);
else return SqrtRec(i, mid-1);
}
};
// { Driver Code Starts.
int main()
{
int t;
cin>>t;
while(t--)
{
long long n;
cin>>n;
Solution obj;
cout << obj.floorSqrt(n) << endl;
}
return 0;
}
// } Driver Code Ends
// LC
class Solution {
public:
int x;
int mySqrt(int x) {
// return pow(x,0.5);
if(x==0 || x ==1) return x;
/**** Linear Way ******/
// unsigned int i=1;
// for(; i*i<=x; i++)
// {
// }
// return i-1;
/**** Recursive Binary Search ******/
// this->x = x;
// return SqrtRec(1, x/2 );
/**** Linear Binary Search ******/
unsigned int i=1, j = x/2, mid=-1;
int ans=-1;
while(i<=j){
mid = i + (j-i)/2;
if(mid == x/mid)
return mid;
if(mid < x/mid)
{
i=mid+1;
}
else{
j=mid-1;
}
}
return j;
}//end
int SqrtRec(int i, int j)
{
if(i>j) return j;
int mid = i + (j-i)/2;
if(mid == x/mid) return mid;
if (mid<x/mid) return SqrtRec(mid+1, j);
else return SqrtRec(i, mid-1);
}
};