FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
Java/Maths/BinaryPow.java at master · rcfgnu/Java · GitHub
rcfgnu
/
Java
Public
forked from
TheAlgorithms/Java
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
Java
/
Maths
/
BinaryPow.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
48 lines (44 loc) · 1 KB
Breadcrumbs
Java
/
Maths
/
BinaryPow.java
Copy path
File metadata and controls
48 lines (44 loc) · 1 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
package
Maths
;
public
class
BinaryPow
{
/**
* Calculate a^p using binary exponentiation
* [Binary-Exponentiation](https://cp-algorithms.com/algebra/binary-exp.html)
*
* @param a the base for exponentiation
* @param p the exponent - must be greater than 0
* @return a^p
*/
public
static
int
binPow
(
int
a
,
int
p
) {
int
res
=
1
;
while
(
p
>
0
) {
if
((
p
&
1
) ==
1
) {
res
=
res
*
a
;
}
a
=
a
*
a
;
p
>>>=
1
;
}
return
res
;
}
/**
* Function for testing binary exponentiation
*
* @param a the base
* @param p the exponent
*/
public
static
void
test
(
int
a
,
int
p
) {
int
res
=
binPow
(
a
,
p
);
assert
res
== (
int
)
Math
.
pow
(
a
,
p
) :
"Incorrect Implementation"
;
System
.
out
.
println
(
a
+
"^"
+
p
+
": "
+
res
);
}
/**
* Main Function to call tests
*
* @param args System Line Arguments
*/
public
static
void
main
(
String
[]
args
) {
// prints 2^15: 32768
test
(
2
,
15
);
// prints 3^9: 19683
test
(
3
,
9
);
}
}
Back
|
FazBrowse Home
|
New Git URL