File tree Expand file tree Collapse file tree 3 files changed +32
-0
lines changed Expand file tree Collapse file tree 3 files changed +32
-0
lines changed Original file line number Diff line number Diff line change @@ -39,6 +39,7 @@ RESTART BUILD
39
39
- [x] [ Extended euclidean algorithm] ( ./src/math/extended_euclidean_algorithm.rs )
40
40
- [x] [ Greatest common divisor] ( ./src/math/greatest_common_divisor.rs )
41
41
- [x] [ Pascal's triangle] ( ./src/math/pascal_triangle.rs )
42
+ - [x] [ Fast power algorithm] ( ./src/math/fast_power.rs )
42
43
43
44
## [ Dynamic Programming] ( ./src/dynamic_programming )
44
45
Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change 1
1
mod extended_euclidean_algorithm;
2
+ mod fast_power;
2
3
mod greatest_common_divisor;
3
4
mod pascal_triangle;
4
5
mod perfect_numbers;
@@ -7,6 +8,7 @@ mod prime_numbers;
7
8
mod trial_division;
8
9
9
10
pub use self :: extended_euclidean_algorithm:: extended_euclidean_algorithm;
11
+ pub use self :: fast_power:: fast_power;
10
12
pub use self :: greatest_common_divisor:: {
11
13
greatest_common_divisor_iterative, greatest_common_divisor_recursive,
12
14
} ;
You can’t perform that action at this time.
0 commit comments