Created
September 10, 2022 22:01
-
-
Save Per48edjes/504abc5d0e38474271b1de9a90e6f17f to your computer and use it in GitHub Desktop.
Implementation of 'fast exponentiation' algorithm in C & Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdint.h> | |
#include <stdio.h> | |
double fast_exp(double base, uint64_t power) | |
{ | |
double result = 1; | |
while (power > 0) | |
{ | |
result *= (power & 1) ? base : 1; | |
power >>= 1; | |
base *= base; | |
} | |
return result; | |
} | |
/* Entry point used for basic testing */ | |
int main(void) | |
{ | |
double base = 3; | |
uint64_t power = 4; | |
double result = fast_exp(base, power); | |
printf("%lf raised to power %llu = %lf\n", base, power, result); | |
base = 2; | |
power = 5; | |
result = fast_exp(base, power); | |
printf("%lf raised to power %llu = %lf\n", base, power, result); | |
base = 6; | |
power = 0; | |
result = fast_exp(base, power); | |
printf("%lf raised to power %llu = %lf\n", base, power, result); | |
return 0; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Union | |
def fast_exp(base: Union[int, float], power: int) -> Union[int, float]: | |
""" | |
Implementation of fast exponentiation for a real `base` raised to | |
natural number `power` | |
>>> fast_exp(3, 4) | |
81 | |
>>> fast_exp(2.0, 4) | |
16.0 | |
>>> fast_exp(2, 5) | |
32 | |
>>> fast_exp(200, 0) | |
1 | |
>>> fast_exp(2.0, 0) | |
1 | |
""" | |
result = 1 | |
while power: | |
if power & 1: # equivalent to `power % 2 == 1` | |
result *= base | |
power >>= 1 # equivalent to `power //= 2` | |
base *= base | |
return result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment