On Fri, 16 Apr 2004 09:34:20 +1200, Bruce Clement
<kiore-at-kiore-dot-> wrote:
>Richard Herring wrote:
>> In message <c5ldnc$ctu$>, Bruce Clement
>> <kiore-at-kiore-dot-> writes
>>
>>> Matt wrote:
>>>
>>>> David wrote:
>>>>
>>>>> How can you write a program in C++ by using loop to control the
>>>>> calculation
>>>>> without the use of library function pwr .For example 3 to the power
>>>>> of 4 (ie
>>>>> 3x3x3x3). Any help will be appreciated
>>>>
>>>> Try posting to comp.lang.c++.homework.
>>>>
>>>
>>> Try something like this. It uses a redundant loop and calculates
>>> X to the power of Y in approximately Y! steps.
>>>
>>>
>[...]
>>
>> Couldn't you use a recursive function here instead of operator* ?
>>
>[...]
>
>LOL, You're evil. I like that in a person.
Real programmers do it with the Peano Axioms
rossum
#include <iostream>
#include <cstdlib>
//-------------------------------------
int successor(int num)
{
int result;
result = ++num;
return result;
} // end successor()
//-------------------------------------
int add(int a, int b)
{
int result;
if (b == 0)
result = a;
else
result = successor(add(a, b - 1));
return result;
} // end add()
//-------------------------------------
int multiply(int a, int b)
{
int result;
if (b == 0)
result = 0;
else
result = add(a, multiply(a, b - 1));
return result;
} // end multiply()
//-------------------------------------
int power(int x, int y)
{
int result = 1;
// An interesting variation, thanks Bruce.
for (int i = y; 0 < i--; )
result = multiply(x, power(x, y - 1));
return result;
} // end power()
//-------------------------------------
int main(int argc, char **argv)
{
std::cout << "Three raised to the power four is "
<< power(3, 4)
<< std::endl;
return EXIT_SUCCESS;
} // end main()
--
The Ultimate Truth is that there is no Ultimate Truth