ADVERTISEMENT
ADVERTISEMENT

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 »



ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.