C# and Exponents

  • Thread starter Thread starter Patrick McGovern
  • Start date Start date
Patrick McGovern said:
Hi, quick question that's driving me nvts. how do i do exponential math in
C#?

Use Math.Pow - there's no exponent operator in C# itself.
 
Patrick,

Take a look at the static Pow method on the Math class.

The bad thing here is that it only takes doubles as an argument.

If you want to use integral values, you could always write the algorithm
yourself (looping through n times, multiplying the result by itself).

Hope this helps.
 
Nicholas Paldino said:
Patrick,

Take a look at the static Pow method on the Math class.

The bad thing here is that it only takes doubles as an argument.

If you want to use integral values, you could always write the
algorithm yourself (looping through n times, multiplying the result by
itself).

Hope this helps.

that helped!!

 
Nicholas Paldino said:
If you want to use integral values, you could always write the algorithm
yourself (looping through n times, multiplying the result by itself).

Hope this helps.

that's horridly inefficient with large exponents though. There's a much
better way to do integer exponents using shifting. Treat the exponent as a
string of bits. Then for each bit that has a value of 1, add the base
shifted left by the bit number. Ie N^13 (13 = 1101) = N + N shifted left 2
bits + N shifted left 3 bits. It doesn't matter much with small exponenets
but with big ones 32 shifts/adds pairs is far faster than millions of
multiplications.
 
for example N^24 = N * N ...... * N (24 times)
OR
N^24 = (((N^2)^2)^2)^3 it requires 5 multiplication rather then 24
 
Back
Top