Sure, here is a Rust function to calculate the power of a number (x^n) recursively using Rust:
Rust
fn power(x: i32, n: i32) -> i32 {
if n == 0 {
return 1;
} else if n == 1 {
return x;
} else {
return x * power(x, n - 1);
}
}
fn main() {
let x = 2;
let n = 3;
let result = power(x, n);
println!("The power of {} to {} is {}", x, n, result);
}
This function first defines a function called power that takes two i32 numbers as input, x and n, and returns the value of x raised to the power of n. The function uses a recursive approach to calculate the power. The base case is when n is 0. In this case, the function simply returns 1. The recursive case is when n is greater than 0. In this case, the function returns x multiplied by the value of x raised to the power of n-1.
The main function of the program then calls the power function with the values 2 and 3 as input. The result of the function call is then printed to the console.
To run the program, you can save it as a file called power.rs and then compile it using the following command:
Code snippet
rustc power.rs
Once the program is compiled, you can run it using the following command:
Code snippet
./power
This will print the following output to the console:
Code snippet
The power of 2 to 3 is 8
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Sure, here is a Rust function to calculate the power of a number (x^n) recursively using Rust:
Rust
This function first defines a function called
powerthat takes two i32 numbers as input, x and n, and returns the value of x raised to the power of n. The function uses a recursive approach to calculate the power. The base case is when n is 0. In this case, the function simply returns 1. The recursive case is when n is greater than 0. In this case, the function returns x multiplied by the value of x raised to the power of n-1.The main function of the program then calls the
powerfunction with the values 2 and 3 as input. The result of the function call is then printed to the console.To run the program, you can save it as a file called
power.rsand then compile it using the following command:Code snippet
Once the program is compiled, you can run it using the following command:
Code snippet
This will print the following output to the console:
Code snippet