Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit1b82826

Browse files
authored
Added Binary Exponentiation Fixes:TheAlgorithms#1943 (TheAlgorithms#1945)
* Added Binary Exponentiation Fixes:TheAlgorithms#1943* tests added in Binary ExponentationTheAlgorithms#1945* Assertion Added
1 parent9c8ad9c commit1b82826

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

‎Maths/BinaryPow.java‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
packageMaths;
2+
3+
publicclassBinaryPow {
4+
/**
5+
* Calculate a^p using binary exponentiation
6+
* [Binary-Exponentiation](https://cp-algorithms.com/algebra/binary-exp.html)
7+
*
8+
* @param a the base for exponentiation
9+
* @param p the exponent - must be greater than 0
10+
* @return a^p
11+
*/
12+
publicstaticintbinPow(inta,intp) {
13+
intres =1;
14+
while (p >0) {
15+
if ((p &1) ==1) {
16+
res =res *a;
17+
}
18+
a =a *a;
19+
p >>>=1;
20+
}
21+
returnres;
22+
}
23+
24+
/**
25+
* Function for testing binary exponentiation
26+
* @param a the base
27+
* @param p the exponent
28+
*/
29+
publicstaticvoidtest(inta,intp) {
30+
intres =binPow(a,p);
31+
assertres == (int)Math.pow(a,p) :"Incorrect Implementation";
32+
System.out.println(a +"^" +p +": " +res);
33+
}
34+
35+
/** Main Function to call tests
36+
*
37+
* @param args System Line Arguments
38+
*/
39+
publicstaticvoidmain(String[]args) {
40+
// prints 2^15: 32768
41+
test(2,15);
42+
43+
// prints 3^9: 19683
44+
test(3,9);
45+
}
46+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp