Open In App

Bash program to find A to the power B

Last Updated : 15 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given two numbers A and B write a shell script to find the value of AB . Examples:

Input: 
2 4
Output:
2 to the power 4 is 16

Input:
1 0
Output:
1 to the power 0 is 1

Approach

A to the power B (AB) means multiplying A, B times. Using a naive approach to solve this problem.

For Example: – A = 2 and B = 3 A3 = 8 which comes by multiplying 2 3 times i.e. 2*2*2 = 8 . BASH]


# Bash Program to find
# A to the power B

# Subroutine to find A
# to the power B
#!/bin/bash
pow()
{
  # value of A
  a=$1

  # value of B
  b=$2

  # c to count counter
  c=1

  # res to store the result
  res=1

  #
  if((b==0));
  then
    res=1
  fi

  if((a==0));
  then
    res=0
  fi

  if((a >= 1 && b >= 1));
  then
    while((c <= b))
    do
      res=$((res * a))
      c=$((c + 1))
    done
  fi

  # Display the result
  echo "$1 to the power $2 is $res"
}

# Driver Code

# input
A=2
B=4

# calling the pow function
pow $A $B

Explanation of Script

  1. the function pow() that calculates the power of a given number A raised to the power of B. Let’s break down the core functionality:
  2. The function pow() takes two arguments A and B as input parameters.
  3. The pow() function is used in the “Driver Code” section to calculate 2 raised to the power of 4, as the values of A and B are set to 2 and 4, respectively.
  4. When the script is executed, it outputs “2 to the power 4 is 16”, indicating that 2^4 equals 16.
  5. It initializes variables a, b, c, and res to store the values of A, B, loop counter, and the result, respectively.
  6. The function checks for two special cases:
    If B is 0, the result (res) is set to 1. This handles the case of A^0, which is always equal to 1.
    If A is 0, the result (res) is set to 0. This handles the case of 0^B, which is always 0 if B is greater than 0.
  7. If both A and B are greater than or equal to 1, the function enters a while loop that runs B times.
  8. Inside the loop, res is updated by multiplying it with A in each iteration, simulating the calculation of A^B.
  9. The loop counter c is also updated to keep track of the number of iterations.
  10. After the loop completes, the function displays the result in the format: “A to the power B is res“.

Output:

428

Time complexity: O(n) as using a while loop

Auxiliary space: O(1)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads