Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

power and exponential functions help (forloops)

Status
Not open for further replies.

aznrurouni

Programmer
Sep 25, 2002
2
US
was wondering if anybody knew how to do powers in a for loop, such as raising (x+1) to a power of n, thanks for any help you guys can give...
 
well, you need to be aware that you can only do so much with an unsigned long/int. They only have 32 bits. You will either need to design a new class to handle LARGE numbers or give yourself a little more space with __int64.

however a for loop is not the quickest way to computer powers

remember that xn can be computed as

value = x * x(n-1)

Knowing this we can also apply another rule

if(n%2 == 0) // power divisable by 2
{
value = x(n/2) * x(n/2);
}


This should get you started with fast computations of powers :)

to do it in a for loop you will just loop "power" times and set value = x*value remembering to initialize value to 1


Matt
 
was wondering how you use the parentheses for the power function, without using the ^ operator, however, i needed the forloop for an accumulation interest function...thanks for your reply...it works that way and if you use a #include <iomanip.h> also the pow (x,n) works, although kinda primative...i actually changed the int to a double for the decimal money values...thanks again
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top