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
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
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 11mod extended_euclidean_algorithm;
2+ mod fast_power;
23mod greatest_common_divisor;
34mod pascal_triangle;
45mod perfect_numbers;
@@ -7,6 +8,7 @@ mod prime_numbers;
78mod trial_division;
89
910pub use self :: extended_euclidean_algorithm:: extended_euclidean_algorithm;
11+ pub use self :: fast_power:: fast_power;
1012pub use self :: greatest_common_divisor:: {
1113 greatest_common_divisor_iterative, greatest_common_divisor_recursive,
1214} ;
You can’t perform that action at this time.
0 commit comments