Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.

Commit 24a92c3

Browse files
arithmetic: fix PerThing pow (#9030)
* arithmetic: add failing test for pow * arithmetic: fix PerThing::pow * Revert back to previous optimisations Co-authored-by: Gav Wood <[email protected]>
1 parent 37bb3ae commit 24a92c3

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

primitives/arithmetic/src/per_things.rs

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -639,20 +639,20 @@ macro_rules! implement_per_thing {
639639
impl Pow<usize> for $name {
640640
type Output = Self;
641641

642-
fn pow(self, exp: usize) -> Self::Output {
642+
fn pow(mut self, exp: usize) -> Self::Output {
643643
if exp == 0 || self.is_one() {
644644
return Self::one()
645645
}
646+
646647
let mut result = self;
647648
let mut exp = exp - 1;
648649
while exp > 0 && !result.is_zero() {
649-
if exp % 2 == 0 {
650-
result = result.square();
651-
exp /= 2;
652-
} else {
650+
if exp % 2 != 0 {
653651
result = result * self;
654652
exp -= 1;
655653
}
654+
self = self.square();
655+
exp /= 2;
656656
}
657657
result
658658
}
@@ -1107,11 +1107,13 @@ macro_rules! implement_per_thing {
11071107
$name::from_parts($max / 2).square(),
11081108
);
11091109

1110-
// x^3
1111-
assert_eq!(
1112-
$name::from_parts($max / 2).saturating_pow(3),
1113-
$name::from_parts($max / 8),
1114-
);
1110+
// x^2 .. x^16
1111+
for n in 1..=16 {
1112+
assert_eq!(
1113+
$name::from_parts($max / 2).saturating_pow(n),
1114+
$name::from_parts(($max as u128 / 2u128.pow(n as u32)) as $type),
1115+
);
1116+
}
11151117

11161118
// 0^n == 0
11171119
assert_eq!(

0 commit comments

Comments
 (0)