forked from trekhleb/javascript-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpower
More file actions
34 lines (28 loc) · 718 Bytes
/
power
File metadata and controls
34 lines (28 loc) · 718 Bytes
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
// Iterative C program to compute modular power
#include <stdio.h>
/* Iterative Function to calculate (x^y)%p in O(log y) */
int power(int x, unsigned int y, int p)
{
int res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
while (y > 0)
{
// If y is odd, multiply x with result
if (y & 1)
res = (res*x) % p;
// y must be even now
y = y>>1; // y = y/2
x = (x*x) % p;
}
return res;
}
// Driver program to test above functions
int main()
{
int x = 2;
int y = 5;
int p = 13;
printf("Power is %u", power(x, y, p));
return 0;
}