-
Notifications
You must be signed in to change notification settings - Fork 294
/
Copy pathExponentiation.cs
45 lines (43 loc) · 1.14 KB
/
Exponentiation.cs
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
namespace Advanced.Algorithms.Numerical;
/// <summary>
/// A fast exponentiation algorithm implementation.
/// </summary>
public class FastExponentiation
{
/// <summary>
/// Computes exponentiation using squaring.
/// </summary>
public static int BySquaring(int @base, int power)
{
while (true)
{
//using the algebraic result
//a^-n = (1/a)^n
if (power < 0)
{
@base = 1 / @base;
power = -power;
continue;
}
switch (power)
{
case 0:
return 1;
case 1:
return @base;
default:
if (power % 2 == 0)
{
@base = @base * @base;
power = power / 2;
continue;
}
//power is odd
else
{
return @base * BySquaring(@base * @base, (power - 1) / 2);
}
}
}
}
}