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
-
the function
pow()
that calculates the power of a given numberA
raised to the power ofB
. Let’s break down the core functionality: -
The function
pow()
takes two argumentsA
andB
as input parameters. -
The
pow()
function is used in the “Driver Code” section to calculate 2 raised to the power of 4, as the values ofA
andB
are set to 2 and 4, respectively. - When the script is executed, it outputs “2 to the power 4 is 16”, indicating that 2^4 equals 16.
-
It initializes variables
a
,b
,c
, andres
to store the values ofA
,B
, loop counter, and the result, respectively. -
The function checks for two special cases:
IfB
is 0, the result (res
) is set to 1. This handles the case ofA^0
, which is always equal to 1.
IfA
is 0, the result (res
) is set to 0. This handles the case of0^B
, which is always 0 ifB
is greater than 0. -
If both
A
andB
are greater than or equal to 1, the function enters awhile
loop that runsB
times. -
Inside the loop,
res
is updated by multiplying it withA
in each iteration, simulating the calculation ofA^B
. -
The loop counter
c
is also updated to keep track of the number of iterations. -
After the loop completes, the function displays the result in the format: “
A
to the powerB
isres
“.
Output:
Time complexity: O(n) as using a while loop
Auxiliary space: O(1)
Article Tags :