Skip to content

Commit ce9fc3c

Browse files
fffzlfkimp2002
andauthored
Add fast power (rust-lang#282)
* Add fast power * Update README Co-authored-by: imp2002 <[email protected]>
1 parent 128e911 commit ce9fc3c

File tree

3 files changed

+32
-0
lines changed

3 files changed

+32
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ RESTART BUILD
3939
- [x] [Extended euclidean algorithm](./src/math/extended_euclidean_algorithm.rs)
4040
- [x] [Greatest common divisor](./src/math/greatest_common_divisor.rs)
4141
- [x] [Pascal's triangle](./src/math/pascal_triangle.rs)
42+
- [x] [Fast power algorithm](./src/math/fast_power.rs)
4243

4344
## [Dynamic Programming](./src/dynamic_programming)
4445

src/math/fast_power.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/// fast_power returns the result of base^power mod modulus
2+
pub fn fast_power(mut base: usize, mut power: usize, modulus: usize) -> usize {
3+
assert!(base >= 1);
4+
5+
let mut res = 1;
6+
while power > 0 {
7+
if power & 1 == 1 {
8+
res = (res * base) % modulus;
9+
}
10+
base = (base * base) % modulus;
11+
power >>= 1;
12+
}
13+
res
14+
}
15+
16+
#[cfg(test)]
17+
mod tests {
18+
use super::*;
19+
20+
#[test]
21+
fn test() {
22+
const MOD: usize = 1000000007;
23+
assert_eq!(fast_power(2, 1, MOD), 2);
24+
assert_eq!(fast_power(2, 2, MOD), 4);
25+
assert_eq!(fast_power(2, 4, MOD), 16);
26+
assert_eq!(fast_power(3, 4, MOD), 81);
27+
assert_eq!(fast_power(2, 100, MOD), 976371285);
28+
}
29+
}

src/math/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
mod extended_euclidean_algorithm;
2+
mod fast_power;
23
mod greatest_common_divisor;
34
mod pascal_triangle;
45
mod perfect_numbers;
@@ -7,6 +8,7 @@ mod prime_numbers;
78
mod trial_division;
89

910
pub use self::extended_euclidean_algorithm::extended_euclidean_algorithm;
11+
pub use self::fast_power::fast_power;
1012
pub use self::greatest_common_divisor::{
1113
greatest_common_divisor_iterative, greatest_common_divisor_recursive,
1214
};

0 commit comments

Comments
 (0)