How to raise a number to a power?

RustOperatorsExponentiation

Rust Problem Overview


I was trying to raise an integer to a power using the caret operator (^), but I am getting surprising results, e.g.:

assert_eq!(2^10, 8);

How can I perform exponentiation in Rust?

Rust Solutions


Solution 1 - Rust

Rust provides exponentiation via methods pow and checked_pow. The latter guards against overflows. Thus, to raise 2 to the power of 10, do:

let base: i32 = 2; // an explicit type is required
assert_eq!(base.pow(10), 1024);

The caret operator ^ is not used for exponentiation, it's the bitwise XOR operator.

Solution 2 - Rust

Here is the simplest method which you can use:

let a = 2; // Can also explicitly define type i.e. i32
let a = i32::pow(a, 10);

It will output "2 raised to the power of 10", i.e.:

> 1024

Solution 3 - Rust

For integers:

fn main() {
   let n = u32::pow(2, 10);
   println!("{}", n == 1024);
}

For floats:

fn main() {
   // example 1
   let f = f32::powf(2.0, 10.0);
   // example 2
   let g = f32::powi(2.0, 10);
   // print
   println!("{}", f == 1024.0 && g == 1024.0);
}

or, since your base is 2, you can also use shift:

fn main() {
   let n = 2 << 9;
   println!("{}", n == 1024);
}

Solution 4 - Rust

I was trying the same thing as the OP. Thanks to the other answer authors.

Here's a variation that works for me:

let n = 2u32.pow(10);

This uses a literal unsigned 32 bit integer to set the type and base, then calls the pow() function on it.

Solution 5 - Rust

Bit shifting is a good way to do this particular case:

assert_eq!(1 << 10, 1024);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatthias BraunView Question on Stackoverflow
Solution 1 - RustMatthias BraunView Answer on Stackoverflow
Solution 2 - RustRohanView Answer on Stackoverflow
Solution 3 - RustZomboView Answer on Stackoverflow
Solution 4 - RustMorganGalpinView Answer on Stackoverflow
Solution 5 - RustChristian OudardView Answer on Stackoverflow