How to Raise a Number to a Power in Rust

Created
Modified

Using pow Method

The pow() function raises a value to the power of exp, using exponentiation by squaring. Note that 0⁰ (pow(0, 0)) returns 1. Mathematically this is undefined.

See the following example:

fn main() {
  let base: i32 = 2;
  println!("{}", base.pow(10));
}
1024

Using i32::pow Method

Here is the simplest method which you can use:

fn main() {
  let a = 2;
  println!("{}", i32::pow(a, 10));

  let b = 2;
  println!("{}", u32::pow(b, 8));

  // For floats:
  println!("{}", f32::powf(2.0, 10.0));
}
1024
256
1024

Related Tags