Skip to content

Latest commit

 

History

History
58 lines (33 loc) · 3.25 KB

File metadata and controls

58 lines (33 loc) · 3.25 KB

 

 

 

 

 

 

Math code snippet to calculate (integer) X to the power of (integer) Y. IntPower is the integer variant of std::pow.

 


#include <cassert> //From http://www.richelbilderbeek.nl/CppIntPower.htm int IntPower(const int base, const int exponent) {   assert(exponent != 0     && "When calculating IntPower(x,0) the result might be zero or one, depending on the context");   assert(exponent > 0);   int result = base;   for (int i=1; i!=exponent; ++i)   {     result*=base;   }   return result; }

 

 

 

 

 

 


#include <iostream> int main() {   assert(IntPower(0,1)==0);   assert(IntPower(0,2)==0);   assert(IntPower(0,3)==0);   assert(IntPower(0,4)==0);   assert(IntPower(1,1)==1);   assert(IntPower(1,2)==1);   assert(IntPower(1,3)==1);   assert(IntPower(1,4)==1);   assert(IntPower(2,1)==2);   assert(IntPower(2,2)==4);   assert(IntPower(2,3)==8);   assert(IntPower(2,4)==16);   assert(IntPower(3,1)==3);   assert(IntPower(3,2)==9);   assert(IntPower(3,3)==27);   assert(IntPower(3,4)==81);   std::cout << "Program finished successfully" << std::endl; }