Write a function to calculate the power of a number (x^n) recursively using Rust.
Write a function to calculate the power of a number (x^n) recursively using Rust.
Student
I am Utpal Vishwas from Uttar Pradesh. Have completed my B. Tech. course from MNNIT campus Prayagraj in 2022. I have good knowledge of computer networking.
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