Rust program to create own Power function without using multiplication (*) and division (/) operators

Rust | Implement Power Function: Write an example to create/implement power function without using multiplication (*) and division (/) operators.
Submitted by Nidhi, on October 07, 2021

Problem Solution:

In this program, we will create our own power function without using multiplication and division operators and print the result.

Program/Source Code:

The source code to create our own Power function without using multiplication(*) and division(/) operators, is given below. The given program is compiled and executed successfully.

// Rust program to create own Power function 
// without using multiplication(*) and 
// division(/) operators

fn MyPow(a:i32, b:i32)->i32
{
  let mut answer:i32 = a;
  let mut increment:i32 = a;
  let mut i=1;
  
  
  if b == 0
  {
    return 1;
  }
 
  while i<b
  {
     let mut j=1;
     while j<a
     {
        answer += increment;
        j=j+1;
     }
     increment = answer;
     i=i+1;
  }
  return answer;
}

fn main() 
{
    let n: i32  = 3;
    let p: i32  = 4;
    let mut rs: i32 = 0;
    
    rs = MyPow(n,p);
    println!("Result is: {}",rs);
}

Output:

Result is: 81

Explanation:

In the above program, we created two functions MyPow() and main(). The MyPow() function is used to calculate the power without using multiplication (*) and division (/) operators and returns the result to the calling function.

In the main() function, we created three integer variables n, p, rs that are initialized with 3,4,0 respectively.  Then we called MyPow() function and assigned the result to the rs variable. After that, we printed the result.

Rust Basic Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.