FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
cpp-lib/src/math.cpp at master · dst/cpp-lib · GitHub
dst
cpp-lib
Repository navigation
Code
Issues
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
cpp-lib
/
src
/
math.cpp
Copy path
More file actions
More file actions
Latest commit
History
History
History
81 lines (64 loc) · 1.45 KB
Breadcrumbs
cpp-lib
/
src
/
math.cpp
Copy path
File metadata and controls
81 lines (64 loc) · 1.45 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
/*
* mathlib.cpp
*
* Created on: Apr 1, 2012
* Author: dst
*/
#
include
<
algorithm
>
#
include
<
cassert
>
#
include
<
cmath
>
#
include
<
vector
>
using
namespace
std
;
template
<
typename
T> T
gcd
(T a, T b) {
return
b >
0
?
gcd
(b, a % b) : a;
}
inline
bool
isPow2
(
int
n) {
return
n >
0
&& (n & (n-
1
)) ==
0
;
}
inline
vector<
int
>
getDigits
(
int
n) {
vector<
int
> digits;
if
(n ==
0
) {
digits.
push_back
(
0
);
return
digits;
}
//
Loop till there's nothing left
while
(n) {
int
lastDigit = n %
10
;
digits.
push_back
(lastDigit);
//
Shift right the number
n /=
10
;
}
reverse
(digits.
begin
(), digits.
end
());
return
digits;
}
//
TODO n over k, prime numbers
//
tests
inline
void
math
() {
//
gcd
assert
(
gcd
(
13
,
7
) ==
1
);
assert
(
gcd
(
21
,
6
) ==
3
);
assert
(
gcd
(
7
,
21
) ==
7
);
//
isPow2
assert
(
isPow2
(
1
));
assert
(
isPow2
(
2
));
assert
(
isPow2
(
4
));
assert
(
isPow2
(
8
));
assert
(!
isPow2
(-
1
));
assert
(!
isPow2
(
0
));
assert
(!
isPow2
(
3
));
assert
(!
isPow2
(
5
));
assert
(!
isPow2
(
6
));
//
getDigits
vector<
int
> digits123 =
getDigits
(
123
);
assert
(digits123[
0
] ==
1
);
assert
(digits123[
1
] ==
2
);
assert
(digits123[
2
] ==
3
);
vector<
int
> digits0 =
getDigits
(
0
);
assert
(digits0[
0
] ==
0
);
//
sqrt
assert
(
sqrt
(
9
) ==
3
);
//
power
assert
(
pow
(
2
,
10
) ==
1024
);
//
TODO: check it
//
assert(pow10(3) == 1000);
}
Back
|
FazBrowse Home
|
New Git URL