forked from msameerfarooq/Hacktoberfest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Check perfect square.cpp
51 lines (43 loc) · 1.01 KB
/
Check perfect square.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
#include <iostream>
using namespace std;
// function to check for
// perfect square number
int checkPerfectSquare(
long int N,
long int start,
long int last)
{
// Find the mid value
// from start and last
long int mid = (start + last) / 2;
if (start > last) {
return -1;
}
// check if we got the number which
// is square root of the perfect
// square number N
if (mid * mid == N) {
return mid;
}
// if the square(mid) is greater than N
// it means only lower values then mid
// will be possibly the square root of N
else if (mid * mid > N) {
return checkPerfectSquare(
N, start, mid - 1);
}
// if the square(mid) is less than N
// it means only higher values then mid
// will be possibly the square root of N
else {
return checkPerfectSquare(
N, mid + 1, last);
}
}
// Driver code
int main()
{
long int N = 65;
cout << checkPerfectSquare(N, 1, N);
return 0;
}