C Program to find the result of a Number raised to another Number (Iterative Approach) (For Small Numbers)


 

// Program by Akash Tripathi (@proakash256) 
 
// If we do it normally by running a loop till that power,
// then its Time Complexity will be O(n).

// To find :- (a ^ b)
// Here a is a Real Number and b is an Integer
 
// if b is even , then we can write it as (a ^ 2) ^ (b / 2)

// if b is odd , then we can write it as (a * (a ^ (b - 1)))
// Now b is even , so we can
// proceed by the first (even) method.
// This method's Time Complexity will be O(log(b)).

#include <stdio.h>
double power(double c , long long d)
{
    if(d == 0
        return 1.0;
    if(d == 1)
        return c;
    double res = 1;
    while(d > 0)
    {
        if((d & 1) != 0// (d % 2) != 0
                        // (Condition for Odd)
        {
            res = res * c;
        }
        d = d >> 1// d = d / 2
        c = c * c;
    }
    return res;
}
int main()
{
    double a;
    long long b;
    printf("Enter the Number : ");
    scanf("%lf" , &a);
    printf("\nEnter the Power : ");
    scanf("%lli" , &b);
    double res;
    if(b < 0)
    {
        res = power((1 / a) , (-b));
    }
    else
    {
        res = power(a , b);           
    }
    printf("\n(%0.2lf ^ %lli) is : %lf\n\n" ,
             a , b , res);
    return 0;
}

Comments