Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you do *integer* exponentiation in C#?

The built-in Math.Pow() function in .NET raises a double base to a double exponent and returns a double result.

What's the best way to do the same with integers?

Added: It seems that one can just cast Math.Pow() result to (int), but will this always produce the correct number and no rounding errors?

like image 617
Roman Starkov Avatar asked Dec 20 '08 18:12

Roman Starkov


People also ask

How do you do exponents with integers in C?

Basically in C exponent value is calculated using the pow() function. pow() is function to get the power of a number, but we have to use #include<math. h> in c/c++ to use that pow() function. then two numbers are passed.


2 Answers

A pretty fast one might be something like this:

int IntPow(int x, uint pow) {     int ret = 1;     while ( pow != 0 )     {         if ( (pow & 1) == 1 )             ret *= x;         x *= x;         pow >>= 1;     }     return ret; } 

Note that this does not allow negative powers. I'll leave that as an exercise to you. :)

Added: Oh yes, almost forgot - also add overflow/underflow checking, or you might be in for a few nasty surprises down the road.

like image 190
Vilx- Avatar answered Sep 22 '22 08:09

Vilx-


LINQ anyone?

public static int Pow(this int bas, int exp) {     return Enumerable           .Repeat(bas, exp)           .Aggregate(1, (a, b) => a * b); } 

usage as extension:

var threeToThePowerOfNine = 3.Pow(9); 
like image 44
3dGrabber Avatar answered Sep 26 '22 08:09

3dGrabber