Wednesday, 29 August 2012

Find power of 2

 

Introduction

  This something simple to understand recursion. Just for a time pass code recipe. :)

Concept

Recursion base condition: 

20 = 1

Generic formula,

pow2(n) = { 1 , when n=0

                  2*pow2(n-1), when n>1

The above formula works out well to find the powers of 2.

Code

double pow2(double val)
{
  if(val == 0)
    return 1;
 
  return 2*pow2(val-1);
}
 
void main()
{
    cout<<pow2(1000);
 
}

Warning

  • This is not an alternate to pow function. The runtime implements it using for loop.

No comments:

Post a Comment