Power in Mathematics in C++



The power of a number is the times a number is multiplied to itself. Also knows as exponent or indices.

a to the power b is b times a is multiplied by itself b times. 7 to the power 2 is 72 also known as 7 square is valued 49.

Some common power values are −

  • A number to the power 0 gives 1.

  • A number to the power 1 gives the same number, as stated some multiplied once is the same.

  • A number to the negative power is n times division. Example, a -3 = 1/a3 or (1/a)*(1/a)*(1/a)

Now, let’s do some programming based on the concept of power.

In this problem, we are given two numbers N and a. And we have to find whether N is equal to a to the power of some number.

Let’s take an example to understand the problem,

Input − N = 64 , a = 2

Output − Yes

A simple and effective solution will be a recursive division of the number. If it perfectly divides the number till the end the return TRUE otherwise FALSE.

Example

Program to show the implementation of our solution

 Live Demo

#include <iostream> using namespace std; bool isAPowerNumber(int x, long int y) {    if (x == 1)       return (y == 1);    long int power = 1;    while (power < y)       power *= x;    return (power == y); } int main() {    int N = 625 , a = 5;    if(isAPowerNumber(a, N))       cout<<N<<" is a power of "<<a;    else       cout<<N<<" is not power of "<<a;    return 0; }

Output

625 is a power of 5
Updated on: 2020-04-17T06:55:32+05:30

178 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements