-
Notifications
You must be signed in to change notification settings - Fork 169
/
square_bit.cpp
49 lines (40 loc) · 901 Bytes
/
square_bit.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
/*
Problem Link: https://www.geeksforgeeks.org/calculate-square-of-a-number-without-using-and-pow/
Calculate square of a number without using *, / and pow()
*/
#include <iostream>
using namespace std;
/*
If n is even, it can be written as
n = 2*x
n2 = (2*x)^2 = 4*x^2
If n is odd, it can be written as
n = 2*x + 1
n2 = (2*x + 1)^2 = 4*x^2 + 4*x + 1
*/
int square(int n) {
// base case
if(n == 0)
return 0;
// negative numbers
if(n < 0)
n = -n;
// get floor(n / 2) using right shift operator
int x = n >> 1;
// recursive calls:
// case-1: n is odd
if(n & 1)
return ((square(x) << 2) + (x << 2) + 1);
// case-2: n is even
else
return (square(x) << 2);
/*
x << 2 is same as x * 4
*/
}
int main() {
int n;
cin >> n;
cout << square(n);
return 0;
}