Algorithm to Calculate The Power Of n^x


0

Q: Write an Algorithm to calculate the power of a number. Input will be n and x, and your algorithm should output the value of nx.

base = input('Enter the base (n): ')
expo = input('Enter the exponent (x): ')

// expo = exponent (x)

float power(int base,  int expo) { 
    if (expo is 0) 
        return 1
    sid = power(base, expo/2)
    if (expo % 2 == 0)
       return sid * sid
    else{
       if(expo > 0)
           return sid * sid * base
       else 
           return sid * sid / base
    }
}

Complexity Analysis

Time Complexity: O(log n)

Space Complexity: O(log n)

Because of “recursive stack space


Like it? Share with your friends!

0
mrwixxsid

0 Comments

Choose A Format
Personality quiz
Series of questions that intends to reveal something about the personality
Trivia quiz
Series of questions with right and wrong answers that intends to check knowledge
Poll
Voting to make decisions or determine opinions
Story
Formatted Text with Embeds and Visuals
List
The Classic Internet Listicles
Countdown
The Classic Internet Countdowns
Open List
Submit your own item and vote up for the best submission
Ranked List
Upvote or downvote to decide the best list item
Meme
Upload your own images to make custom memes
Video
Youtube and Vimeo Embeds
Audio
Soundcloud or Mixcloud Embeds
Image
Photo or GIF
Gif
GIF format